babylon.max.js 4.5 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459794607946179462794637946479465794667946779468794697947079471794727947379474794757947679477794787947979480794817948279483794847948579486794877948879489794907949179492794937949479495794967949779498794997950079501795027950379504795057950679507795087950979510795117951279513795147951579516795177951879519795207952179522795237952479525795267952779528795297953079531795327953379534795357953679537795387953979540795417954279543795447954579546795477954879549795507955179552795537955479555795567955779558795597956079561795627956379564795657956679567795687956979570795717957279573795747957579576795777957879579795807958179582795837958479585795867958779588795897959079591795927959379594795957959679597795987959979600796017960279603796047960579606796077960879609796107961179612796137961479615796167961779618796197962079621796227962379624796257962679627796287962979630796317963279633796347963579636796377963879639796407964179642796437964479645796467964779648796497965079651796527965379654796557965679657796587965979660796617966279663796647966579666796677966879669796707967179672796737967479675796767967779678796797968079681796827968379684796857968679687796887968979690796917969279693796947969579696796977969879699797007970179702797037970479705797067970779708797097971079711797127971379714797157971679717797187971979720797217972279723797247972579726797277972879729797307973179732797337973479735797367973779738797397974079741797427974379744797457974679747797487974979750797517975279753797547975579756797577975879759797607976179762797637976479765797667976779768797697977079771797727977379774797757977679777797787977979780797817978279783797847978579786797877978879789797907979179792797937979479795797967979779798797997980079801798027980379804798057980679807798087980979810798117981279813798147981579816798177981879819798207982179822798237982479825798267982779828798297983079831798327983379834798357983679837798387983979840798417984279843798447984579846798477984879849798507985179852798537985479855798567985779858798597986079861798627986379864798657986679867798687986979870798717987279873798747987579876798777987879879798807988179882798837988479885798867988779888798897989079891798927989379894798957989679897798987989979900799017990279903799047990579906799077990879909799107991179912799137991479915799167991779918799197992079921799227992379924799257992679927799287992979930799317993279933799347993579936799377993879939799407994179942799437994479945799467994779948799497995079951799527995379954799557995679957799587995979960799617996279963799647996579966799677996879969799707997179972799737997479975799767997779978799797998079981799827998379984799857998679987799887998979990799917999279993799947999579996799977999879999800008000180002800038000480005800068000780008800098001080011800128001380014800158001680017800188001980020800218002280023800248002580026800278002880029800308003180032800338003480035800368003780038800398004080041800428004380044800458004680047800488004980050800518005280053800548005580056800578005880059800608006180062800638006480065800668006780068800698007080071800728007380074800758007680077800788007980080800818008280083800848008580086800878008880089800908009180092800938009480095800968009780098800998010080101801028010380104801058010680107801088010980110801118011280113801148011580116801178011880119801208012180122801238012480125801268012780128801298013080131801328013380134801358013680137801388013980140801418014280143801448014580146801478014880149801508015180152801538015480155801568015780158801598016080161801628016380164801658016680167801688016980170801718017280173801748017580176801778017880179801808018180182801838018480185801868018780188801898019080191801928019380194801958019680197801988019980200802018020280203802048020580206802078020880209802108021180212802138021480215802168021780218802198022080221802228022380224802258022680227802288022980230802318023280233802348023580236802378023880239802408024180242802438024480245802468024780248802498025080251802528025380254802558025680257802588025980260802618026280263802648026580266802678026880269802708027180272802738027480275802768027780278802798028080281802828028380284802858028680287802888028980290802918029280293802948029580296802978029880299803008030180302803038030480305803068030780308803098031080311803128031380314803158031680317803188031980320803218032280323803248032580326803278032880329803308033180332803338033480335803368033780338803398034080341803428034380344803458034680347803488034980350803518035280353803548035580356803578035880359803608036180362803638036480365803668036780368803698037080371803728037380374803758037680377803788037980380803818038280383803848038580386803878038880389803908039180392803938039480395803968039780398803998040080401804028040380404804058040680407804088040980410804118041280413804148041580416804178041880419804208042180422804238042480425804268042780428804298043080431804328043380434804358043680437804388043980440804418044280443804448044580446804478044880449804508045180452804538045480455804568045780458804598046080461804628046380464804658046680467804688046980470804718047280473804748047580476804778047880479804808048180482804838048480485804868048780488804898049080491804928049380494804958049680497804988049980500805018050280503805048050580506805078050880509805108051180512805138051480515805168051780518805198052080521805228052380524805258052680527805288052980530805318053280533805348053580536805378053880539805408054180542805438054480545805468054780548805498055080551805528055380554805558055680557805588055980560805618056280563805648056580566805678056880569805708057180572805738057480575805768057780578805798058080581805828058380584805858058680587805888058980590805918059280593805948059580596805978059880599806008060180602806038060480605806068060780608806098061080611806128061380614806158061680617806188061980620806218062280623806248062580626806278062880629806308063180632806338063480635806368063780638806398064080641806428064380644806458064680647806488064980650806518065280653806548065580656806578065880659806608066180662806638066480665806668066780668806698067080671806728067380674806758067680677806788067980680806818068280683806848068580686806878068880689806908069180692806938069480695806968069780698806998070080701807028070380704807058070680707807088070980710807118071280713807148071580716807178071880719807208072180722807238072480725807268072780728807298073080731807328073380734807358073680737807388073980740807418074280743807448074580746807478074880749807508075180752807538075480755807568075780758807598076080761807628076380764807658076680767807688076980770807718077280773807748077580776807778077880779807808078180782807838078480785807868078780788807898079080791807928079380794807958079680797807988079980800808018080280803808048080580806808078080880809808108081180812808138081480815808168081780818808198082080821808228082380824808258082680827808288082980830808318083280833808348083580836808378083880839808408084180842808438084480845808468084780848808498085080851808528085380854808558085680857808588085980860808618086280863808648086580866808678086880869808708087180872808738087480875808768087780878808798088080881808828088380884808858088680887808888088980890808918089280893808948089580896808978089880899809008090180902809038090480905809068090780908809098091080911809128091380914809158091680917809188091980920809218092280923809248092580926809278092880929809308093180932809338093480935809368093780938809398094080941809428094380944809458094680947809488094980950809518095280953809548095580956809578095880959809608096180962809638096480965809668096780968809698097080971809728097380974809758097680977809788097980980809818098280983809848098580986809878098880989809908099180992809938099480995809968099780998809998100081001810028100381004810058100681007810088100981010810118101281013810148101581016810178101881019810208102181022810238102481025810268102781028810298103081031810328103381034810358103681037810388103981040810418104281043810448104581046810478104881049810508105181052810538105481055810568105781058810598106081061810628106381064810658106681067810688106981070810718107281073810748107581076810778107881079810808108181082810838108481085810868108781088810898109081091810928109381094810958109681097810988109981100811018110281103811048110581106811078110881109811108111181112811138111481115811168111781118811198112081121811228112381124811258112681127811288112981130811318113281133811348113581136811378113881139811408114181142811438114481145811468114781148811498115081151811528115381154811558115681157811588115981160811618116281163811648116581166811678116881169811708117181172811738117481175811768117781178811798118081181811828118381184811858118681187811888118981190811918119281193811948119581196811978119881199812008120181202812038120481205812068120781208812098121081211812128121381214812158121681217812188121981220812218122281223812248122581226812278122881229812308123181232812338123481235812368123781238812398124081241812428124381244812458124681247812488124981250812518125281253812548125581256812578125881259812608126181262812638126481265812668126781268812698127081271812728127381274812758127681277812788127981280812818128281283812848128581286812878128881289812908129181292812938129481295812968129781298812998130081301813028130381304813058130681307813088130981310813118131281313813148131581316813178131881319813208132181322813238132481325813268132781328813298133081331813328133381334813358133681337813388133981340813418134281343813448134581346813478134881349813508135181352813538135481355813568135781358813598136081361813628136381364813658136681367813688136981370813718137281373813748137581376813778137881379813808138181382813838138481385813868138781388813898139081391813928139381394813958139681397813988139981400814018140281403814048140581406814078140881409814108141181412814138141481415814168141781418814198142081421814228142381424814258142681427814288142981430814318143281433814348143581436814378143881439814408144181442814438144481445814468144781448814498145081451814528145381454814558145681457814588145981460814618146281463814648146581466814678146881469814708147181472814738147481475814768147781478814798148081481814828148381484814858148681487814888148981490814918149281493814948149581496814978149881499815008150181502815038150481505815068150781508815098151081511815128151381514815158151681517815188151981520815218152281523815248152581526815278152881529815308153181532815338153481535815368153781538815398154081541815428154381544815458154681547815488154981550815518155281553815548155581556815578155881559815608156181562815638156481565815668156781568815698157081571815728157381574815758157681577815788157981580815818158281583815848158581586815878158881589815908159181592815938159481595815968159781598815998160081601816028160381604816058160681607816088160981610816118161281613816148161581616816178161881619816208162181622816238162481625816268162781628816298163081631816328163381634816358163681637816388163981640816418164281643816448164581646816478164881649816508165181652816538165481655816568165781658816598166081661816628166381664816658166681667816688166981670816718167281673816748167581676816778167881679816808168181682816838168481685816868168781688816898169081691816928169381694816958169681697816988169981700817018170281703817048170581706817078170881709817108171181712817138171481715817168171781718817198172081721817228172381724817258172681727817288172981730817318173281733817348173581736817378173881739817408174181742817438174481745817468174781748817498175081751817528175381754817558175681757817588175981760817618176281763817648176581766817678176881769817708177181772817738177481775817768177781778817798178081781817828178381784817858178681787817888178981790817918179281793817948179581796817978179881799818008180181802818038180481805818068180781808818098181081811818128181381814818158181681817818188181981820818218182281823818248182581826818278182881829818308183181832818338183481835818368183781838818398184081841818428184381844818458184681847818488184981850818518185281853818548185581856818578185881859818608186181862818638186481865818668186781868818698187081871818728187381874818758187681877818788187981880818818188281883818848188581886818878188881889818908189181892818938189481895818968189781898818998190081901819028190381904819058190681907819088190981910819118191281913819148191581916819178191881919819208192181922819238192481925819268192781928819298193081931819328193381934819358193681937819388193981940819418194281943819448194581946819478194881949819508195181952819538195481955819568195781958819598196081961819628196381964819658196681967819688196981970819718197281973819748197581976819778197881979819808198181982819838198481985819868198781988819898199081991819928199381994819958199681997819988199982000820018200282003820048200582006820078200882009820108201182012820138201482015820168201782018820198202082021820228202382024820258202682027820288202982030820318203282033820348203582036820378203882039820408204182042820438204482045820468204782048820498205082051820528205382054820558205682057820588205982060820618206282063820648206582066820678206882069820708207182072820738207482075820768207782078820798208082081820828208382084820858208682087820888208982090820918209282093820948209582096820978209882099821008210182102821038210482105821068210782108821098211082111821128211382114821158211682117821188211982120821218212282123821248212582126821278212882129821308213182132821338213482135821368213782138821398214082141821428214382144821458214682147821488214982150821518215282153821548215582156821578215882159821608216182162821638216482165821668216782168821698217082171821728217382174821758217682177821788217982180821818218282183821848218582186821878218882189821908219182192821938219482195821968219782198821998220082201822028220382204822058220682207822088220982210822118221282213822148221582216822178221882219822208222182222822238222482225822268222782228822298223082231822328223382234822358223682237822388223982240822418224282243822448224582246822478224882249822508225182252822538225482255822568225782258822598226082261822628226382264822658226682267822688226982270822718227282273822748227582276822778227882279822808228182282822838228482285822868228782288822898229082291822928229382294822958229682297822988229982300823018230282303823048230582306823078230882309823108231182312823138231482315823168231782318823198232082321823228232382324823258232682327823288232982330823318233282333823348233582336823378233882339823408234182342823438234482345823468234782348823498235082351823528235382354823558235682357823588235982360823618236282363823648236582366823678236882369823708237182372823738237482375823768237782378823798238082381823828238382384823858238682387823888238982390823918239282393823948239582396823978239882399824008240182402824038240482405824068240782408824098241082411824128241382414824158241682417824188241982420824218242282423824248242582426824278242882429824308243182432824338243482435824368243782438824398244082441824428244382444824458244682447824488244982450824518245282453824548245582456824578245882459824608246182462824638246482465824668246782468824698247082471824728247382474824758247682477824788247982480824818248282483824848248582486824878248882489824908249182492824938249482495824968249782498824998250082501825028250382504825058250682507825088250982510825118251282513825148251582516825178251882519825208252182522825238252482525825268252782528825298253082531825328253382534825358253682537825388253982540825418254282543825448254582546825478254882549825508255182552825538255482555825568255782558825598256082561825628256382564825658256682567825688256982570825718257282573825748257582576825778257882579825808258182582825838258482585825868258782588825898259082591825928259382594825958259682597825988259982600826018260282603826048260582606826078260882609826108261182612826138261482615826168261782618826198262082621826228262382624826258262682627826288262982630826318263282633826348263582636826378263882639826408264182642826438264482645826468264782648826498265082651826528265382654826558265682657826588265982660826618266282663826648266582666826678266882669826708267182672826738267482675826768267782678826798268082681826828268382684826858268682687826888268982690826918269282693826948269582696826978269882699827008270182702827038270482705827068270782708827098271082711827128271382714827158271682717827188271982720827218272282723827248272582726827278272882729827308273182732827338273482735827368273782738827398274082741827428274382744827458274682747827488274982750827518275282753827548275582756827578275882759827608276182762827638276482765827668276782768827698277082771827728277382774827758277682777827788277982780827818278282783827848278582786827878278882789827908279182792827938279482795827968279782798827998280082801828028280382804828058280682807828088280982810828118281282813828148281582816828178281882819828208282182822828238282482825828268282782828828298283082831828328283382834828358283682837828388283982840828418284282843828448284582846828478284882849828508285182852828538285482855828568285782858828598286082861828628286382864828658286682867828688286982870828718287282873828748287582876828778287882879828808288182882828838288482885828868288782888828898289082891828928289382894828958289682897828988289982900829018290282903829048290582906829078290882909829108291182912829138291482915829168291782918829198292082921829228292382924829258292682927829288292982930829318293282933829348293582936829378293882939829408294182942829438294482945829468294782948829498295082951829528295382954829558295682957829588295982960829618296282963829648296582966829678296882969829708297182972829738297482975829768297782978829798298082981829828298382984829858298682987829888298982990829918299282993829948299582996829978299882999830008300183002830038300483005830068300783008830098301083011830128301383014830158301683017830188301983020830218302283023830248302583026830278302883029830308303183032830338303483035830368303783038830398304083041830428304383044830458304683047830488304983050830518305283053830548305583056830578305883059830608306183062830638306483065830668306783068830698307083071830728307383074830758307683077830788307983080830818308283083830848308583086830878308883089830908309183092830938309483095830968309783098830998310083101831028310383104831058310683107831088310983110831118311283113831148311583116831178311883119831208312183122831238312483125831268312783128831298313083131831328313383134831358313683137831388313983140831418314283143831448314583146831478314883149831508315183152831538315483155831568315783158831598316083161831628316383164831658316683167831688316983170831718317283173831748317583176831778317883179831808318183182831838318483185831868318783188831898319083191831928319383194831958319683197831988319983200832018320283203832048320583206832078320883209832108321183212832138321483215832168321783218832198322083221832228322383224832258322683227832288322983230832318323283233832348323583236832378323883239832408324183242832438324483245832468324783248832498325083251832528325383254832558325683257832588325983260832618326283263832648326583266832678326883269832708327183272832738327483275832768327783278832798328083281832828328383284832858328683287832888328983290832918329283293832948329583296832978329883299833008330183302833038330483305833068330783308833098331083311833128331383314833158331683317833188331983320833218332283323833248332583326833278332883329833308333183332833338333483335833368333783338833398334083341833428334383344833458334683347833488334983350833518335283353833548335583356833578335883359833608336183362833638336483365833668336783368833698337083371833728337383374833758337683377833788337983380833818338283383833848338583386833878338883389833908339183392833938339483395833968339783398833998340083401834028340383404834058340683407834088340983410834118341283413834148341583416834178341883419834208342183422834238342483425834268342783428834298343083431834328343383434834358343683437834388343983440834418344283443834448344583446834478344883449834508345183452834538345483455834568345783458834598346083461834628346383464834658346683467834688346983470834718347283473834748347583476834778347883479834808348183482834838348483485834868348783488834898349083491834928349383494834958349683497834988349983500835018350283503835048350583506835078350883509835108351183512835138351483515835168351783518835198352083521835228352383524835258352683527835288352983530835318353283533835348353583536835378353883539835408354183542835438354483545835468354783548835498355083551835528355383554835558355683557835588355983560835618356283563835648356583566835678356883569835708357183572835738357483575835768357783578835798358083581835828358383584835858358683587835888358983590835918359283593835948359583596835978359883599836008360183602836038360483605836068360783608836098361083611836128361383614836158361683617836188361983620836218362283623836248362583626836278362883629836308363183632836338363483635836368363783638836398364083641836428364383644836458364683647836488364983650836518365283653836548365583656836578365883659836608366183662836638366483665836668366783668836698367083671836728367383674836758367683677836788367983680836818368283683836848368583686836878368883689836908369183692836938369483695836968369783698836998370083701837028370383704837058370683707837088370983710837118371283713837148371583716837178371883719837208372183722837238372483725837268372783728837298373083731837328373383734837358373683737837388373983740837418374283743837448374583746837478374883749837508375183752837538375483755837568375783758837598376083761837628376383764837658376683767837688376983770837718377283773837748377583776837778377883779837808378183782837838378483785837868378783788837898379083791837928379383794837958379683797837988379983800838018380283803838048380583806838078380883809838108381183812838138381483815838168381783818838198382083821838228382383824838258382683827838288382983830838318383283833838348383583836838378383883839838408384183842838438384483845838468384783848838498385083851838528385383854838558385683857838588385983860838618386283863838648386583866838678386883869838708387183872838738387483875838768387783878838798388083881838828388383884838858388683887838888388983890838918389283893838948389583896838978389883899839008390183902839038390483905839068390783908839098391083911839128391383914839158391683917839188391983920839218392283923839248392583926839278392883929839308393183932839338393483935839368393783938839398394083941839428394383944839458394683947839488394983950839518395283953839548395583956839578395883959839608396183962839638396483965839668396783968839698397083971839728397383974839758397683977839788397983980839818398283983839848398583986839878398883989839908399183992839938399483995839968399783998839998400084001840028400384004840058400684007840088400984010840118401284013840148401584016840178401884019840208402184022840238402484025840268402784028840298403084031840328403384034840358403684037840388403984040840418404284043840448404584046840478404884049840508405184052840538405484055840568405784058840598406084061840628406384064840658406684067840688406984070840718407284073840748407584076840778407884079840808408184082840838408484085840868408784088840898409084091840928409384094840958409684097840988409984100841018410284103841048410584106841078410884109841108411184112841138411484115841168411784118841198412084121841228412384124841258412684127841288412984130841318413284133841348413584136841378413884139841408414184142841438414484145841468414784148841498415084151841528415384154841558415684157841588415984160841618416284163841648416584166841678416884169841708417184172841738417484175841768417784178841798418084181841828418384184841858418684187841888418984190841918419284193841948419584196841978419884199842008420184202842038420484205842068420784208842098421084211842128421384214842158421684217842188421984220842218422284223842248422584226842278422884229842308423184232842338423484235842368423784238842398424084241842428424384244842458424684247842488424984250842518425284253842548425584256842578425884259842608426184262842638426484265842668426784268842698427084271842728427384274842758427684277842788427984280842818428284283842848428584286842878428884289842908429184292842938429484295842968429784298842998430084301843028430384304843058430684307843088430984310843118431284313843148431584316843178431884319843208432184322843238432484325843268432784328843298433084331843328433384334843358433684337843388433984340843418434284343843448434584346843478434884349843508435184352843538435484355843568435784358843598436084361843628436384364843658436684367843688436984370843718437284373843748437584376843778437884379843808438184382843838438484385843868438784388843898439084391843928439384394843958439684397843988439984400844018440284403844048440584406844078440884409844108441184412844138441484415844168441784418844198442084421844228442384424844258442684427844288442984430844318443284433844348443584436844378443884439844408444184442844438444484445844468444784448844498445084451844528445384454844558445684457844588445984460844618446284463844648446584466844678446884469844708447184472844738447484475844768447784478844798448084481844828448384484844858448684487844888448984490844918449284493844948449584496844978449884499845008450184502845038450484505845068450784508845098451084511845128451384514845158451684517845188451984520845218452284523845248452584526845278452884529845308453184532845338453484535845368453784538845398454084541845428454384544845458454684547845488454984550845518455284553845548455584556845578455884559845608456184562845638456484565845668456784568845698457084571845728457384574845758457684577845788457984580845818458284583845848458584586845878458884589845908459184592845938459484595845968459784598845998460084601846028460384604846058460684607846088460984610846118461284613846148461584616846178461884619846208462184622846238462484625846268462784628846298463084631846328463384634846358463684637846388463984640846418464284643846448464584646846478464884649846508465184652846538465484655846568465784658846598466084661846628466384664846658466684667846688466984670846718467284673846748467584676846778467884679846808468184682846838468484685846868468784688846898469084691846928469384694846958469684697846988469984700847018470284703847048470584706847078470884709847108471184712847138471484715847168471784718847198472084721847228472384724847258472684727847288472984730847318473284733847348473584736847378473884739847408474184742847438474484745847468474784748847498475084751847528475384754847558475684757847588475984760847618476284763847648476584766847678476884769847708477184772847738477484775847768477784778847798478084781847828478384784847858478684787847888478984790847918479284793847948479584796847978479884799848008480184802848038480484805848068480784808848098481084811848128481384814848158481684817848188481984820848218482284823848248482584826848278482884829848308483184832848338483484835848368483784838848398484084841848428484384844848458484684847848488484984850848518485284853848548485584856848578485884859848608486184862848638486484865848668486784868848698487084871848728487384874848758487684877848788487984880848818488284883848848488584886848878488884889848908489184892848938489484895848968489784898848998490084901849028490384904849058490684907849088490984910849118491284913849148491584916849178491884919849208492184922849238492484925849268492784928849298493084931849328493384934849358493684937849388493984940849418494284943849448494584946849478494884949849508495184952849538495484955849568495784958849598496084961849628496384964849658496684967849688496984970849718497284973849748497584976849778497884979849808498184982849838498484985849868498784988849898499084991849928499384994849958499684997849988499985000850018500285003850048500585006850078500885009850108501185012850138501485015850168501785018850198502085021850228502385024850258502685027850288502985030850318503285033850348503585036850378503885039850408504185042850438504485045850468504785048850498505085051850528505385054850558505685057850588505985060850618506285063850648506585066850678506885069850708507185072850738507485075850768507785078850798508085081850828508385084850858508685087850888508985090850918509285093850948509585096850978509885099851008510185102851038510485105851068510785108851098511085111851128511385114851158511685117851188511985120851218512285123851248512585126851278512885129851308513185132851338513485135851368513785138851398514085141851428514385144851458514685147851488514985150851518515285153851548515585156851578515885159851608516185162851638516485165851668516785168851698517085171851728517385174851758517685177851788517985180851818518285183851848518585186851878518885189851908519185192851938519485195851968519785198851998520085201852028520385204852058520685207852088520985210852118521285213852148521585216852178521885219852208522185222852238522485225852268522785228852298523085231852328523385234852358523685237852388523985240852418524285243852448524585246852478524885249852508525185252852538525485255852568525785258852598526085261852628526385264852658526685267852688526985270852718527285273852748527585276852778527885279852808528185282852838528485285852868528785288852898529085291852928529385294852958529685297852988529985300853018530285303853048530585306853078530885309853108531185312853138531485315853168531785318853198532085321853228532385324853258532685327853288532985330853318533285333853348533585336853378533885339853408534185342853438534485345853468534785348853498535085351853528535385354853558535685357853588535985360853618536285363853648536585366853678536885369853708537185372853738537485375853768537785378853798538085381853828538385384853858538685387853888538985390853918539285393853948539585396853978539885399854008540185402854038540485405854068540785408854098541085411854128541385414854158541685417854188541985420854218542285423854248542585426854278542885429854308543185432854338543485435854368543785438854398544085441854428544385444854458544685447854488544985450854518545285453854548545585456854578545885459854608546185462854638546485465854668546785468854698547085471854728547385474854758547685477854788547985480854818548285483854848548585486854878548885489854908549185492854938549485495854968549785498854998550085501855028550385504855058550685507855088550985510855118551285513855148551585516855178551885519855208552185522855238552485525855268552785528855298553085531855328553385534855358553685537855388553985540855418554285543855448554585546855478554885549855508555185552855538555485555855568555785558855598556085561855628556385564855658556685567855688556985570855718557285573855748557585576855778557885579855808558185582855838558485585855868558785588855898559085591855928559385594855958559685597855988559985600856018560285603856048560585606856078560885609856108561185612856138561485615856168561785618856198562085621856228562385624856258562685627856288562985630856318563285633856348563585636856378563885639856408564185642856438564485645856468564785648856498565085651856528565385654856558565685657856588565985660856618566285663856648566585666856678566885669856708567185672856738567485675856768567785678856798568085681856828568385684856858568685687856888568985690856918569285693856948569585696856978569885699857008570185702857038570485705857068570785708857098571085711857128571385714857158571685717857188571985720857218572285723857248572585726857278572885729857308573185732857338573485735857368573785738857398574085741857428574385744857458574685747857488574985750857518575285753857548575585756857578575885759857608576185762857638576485765857668576785768857698577085771857728577385774857758577685777857788577985780857818578285783857848578585786857878578885789857908579185792857938579485795857968579785798857998580085801858028580385804858058580685807858088580985810858118581285813858148581585816858178581885819858208582185822858238582485825858268582785828858298583085831858328583385834858358583685837858388583985840858418584285843858448584585846858478584885849858508585185852858538585485855858568585785858858598586085861858628586385864858658586685867858688586985870858718587285873858748587585876858778587885879858808588185882858838588485885858868588785888858898589085891858928589385894858958589685897858988589985900859018590285903859048590585906859078590885909859108591185912859138591485915859168591785918859198592085921859228592385924859258592685927859288592985930859318593285933859348593585936859378593885939859408594185942859438594485945859468594785948859498595085951859528595385954859558595685957859588595985960859618596285963859648596585966859678596885969859708597185972859738597485975859768597785978859798598085981859828598385984859858598685987859888598985990859918599285993859948599585996859978599885999860008600186002860038600486005860068600786008860098601086011860128601386014860158601686017860188601986020860218602286023860248602586026860278602886029860308603186032860338603486035860368603786038860398604086041860428604386044860458604686047860488604986050860518605286053860548605586056860578605886059860608606186062860638606486065860668606786068860698607086071860728607386074860758607686077860788607986080860818608286083860848608586086860878608886089860908609186092860938609486095860968609786098860998610086101861028610386104861058610686107861088610986110861118611286113861148611586116861178611886119861208612186122861238612486125861268612786128861298613086131861328613386134861358613686137861388613986140861418614286143861448614586146861478614886149861508615186152861538615486155861568615786158861598616086161861628616386164861658616686167861688616986170861718617286173861748617586176861778617886179861808618186182861838618486185861868618786188861898619086191861928619386194861958619686197861988619986200862018620286203862048620586206862078620886209862108621186212862138621486215862168621786218862198622086221862228622386224862258622686227862288622986230862318623286233862348623586236862378623886239862408624186242862438624486245862468624786248862498625086251862528625386254862558625686257862588625986260862618626286263862648626586266862678626886269862708627186272862738627486275862768627786278862798628086281862828628386284862858628686287862888628986290862918629286293862948629586296862978629886299863008630186302863038630486305863068630786308863098631086311863128631386314863158631686317863188631986320863218632286323863248632586326863278632886329863308633186332863338633486335863368633786338863398634086341863428634386344863458634686347863488634986350863518635286353863548635586356863578635886359863608636186362863638636486365863668636786368863698637086371863728637386374863758637686377863788637986380863818638286383863848638586386863878638886389863908639186392863938639486395863968639786398863998640086401864028640386404864058640686407864088640986410864118641286413864148641586416864178641886419864208642186422864238642486425864268642786428864298643086431864328643386434864358643686437864388643986440864418644286443864448644586446864478644886449864508645186452864538645486455864568645786458864598646086461864628646386464864658646686467864688646986470864718647286473864748647586476864778647886479864808648186482864838648486485864868648786488864898649086491864928649386494864958649686497864988649986500865018650286503865048650586506865078650886509865108651186512865138651486515865168651786518865198652086521865228652386524865258652686527865288652986530865318653286533865348653586536865378653886539865408654186542865438654486545865468654786548865498655086551865528655386554865558655686557865588655986560865618656286563865648656586566865678656886569865708657186572865738657486575865768657786578865798658086581865828658386584865858658686587865888658986590865918659286593865948659586596865978659886599866008660186602866038660486605866068660786608866098661086611866128661386614866158661686617866188661986620866218662286623866248662586626866278662886629866308663186632866338663486635866368663786638866398664086641866428664386644866458664686647866488664986650866518665286653866548665586656866578665886659866608666186662866638666486665866668666786668866698667086671866728667386674866758667686677866788667986680866818668286683866848668586686866878668886689866908669186692866938669486695866968669786698866998670086701867028670386704867058670686707867088670986710867118671286713867148671586716867178671886719867208672186722867238672486725867268672786728867298673086731867328673386734867358673686737867388673986740867418674286743867448674586746867478674886749867508675186752867538675486755867568675786758867598676086761867628676386764867658676686767867688676986770867718677286773867748677586776867778677886779867808678186782867838678486785867868678786788867898679086791867928679386794867958679686797867988679986800868018680286803868048680586806868078680886809868108681186812868138681486815868168681786818868198682086821868228682386824868258682686827868288682986830868318683286833868348683586836868378683886839868408684186842868438684486845868468684786848868498685086851868528685386854868558685686857868588685986860868618686286863868648686586866868678686886869868708687186872868738687486875868768687786878868798688086881868828688386884868858688686887868888688986890868918689286893868948689586896868978689886899869008690186902869038690486905869068690786908869098691086911869128691386914869158691686917869188691986920869218692286923869248692586926869278692886929869308693186932869338693486935869368693786938869398694086941869428694386944869458694686947869488694986950869518695286953869548695586956869578695886959869608696186962869638696486965869668696786968869698697086971869728697386974869758697686977869788697986980869818698286983869848698586986869878698886989869908699186992869938699486995869968699786998869998700087001870028700387004870058700687007870088700987010870118701287013870148701587016870178701887019870208702187022870238702487025870268702787028870298703087031870328703387034870358703687037870388703987040870418704287043870448704587046870478704887049870508705187052870538705487055870568705787058870598706087061870628706387064870658706687067870688706987070870718707287073870748707587076870778707887079870808708187082870838708487085870868708787088870898709087091870928709387094870958709687097870988709987100871018710287103871048710587106871078710887109871108711187112871138711487115871168711787118871198712087121871228712387124871258712687127871288712987130871318713287133871348713587136871378713887139871408714187142871438714487145871468714787148871498715087151871528715387154871558715687157871588715987160871618716287163871648716587166871678716887169871708717187172871738717487175871768717787178871798718087181871828718387184871858718687187871888718987190871918719287193871948719587196871978719887199872008720187202872038720487205872068720787208872098721087211872128721387214872158721687217872188721987220872218722287223872248722587226872278722887229872308723187232872338723487235872368723787238872398724087241872428724387244872458724687247872488724987250872518725287253872548725587256872578725887259872608726187262872638726487265872668726787268872698727087271872728727387274872758727687277872788727987280872818728287283872848728587286872878728887289872908729187292872938729487295872968729787298872998730087301873028730387304873058730687307873088730987310873118731287313873148731587316873178731887319873208732187322873238732487325873268732787328873298733087331873328733387334873358733687337873388733987340873418734287343873448734587346873478734887349873508735187352873538735487355873568735787358873598736087361873628736387364873658736687367873688736987370873718737287373873748737587376873778737887379873808738187382873838738487385873868738787388873898739087391873928739387394873958739687397873988739987400874018740287403874048740587406874078740887409874108741187412874138741487415874168741787418874198742087421874228742387424874258742687427874288742987430874318743287433874348743587436874378743887439874408744187442874438744487445874468744787448874498745087451874528745387454874558745687457874588745987460874618746287463874648746587466874678746887469874708747187472874738747487475874768747787478874798748087481874828748387484874858748687487874888748987490874918749287493874948749587496874978749887499875008750187502875038750487505875068750787508875098751087511875128751387514875158751687517875188751987520875218752287523875248752587526875278752887529875308753187532875338753487535875368753787538875398754087541875428754387544875458754687547875488754987550875518755287553875548755587556875578755887559875608756187562875638756487565875668756787568875698757087571875728757387574875758757687577875788757987580875818758287583875848758587586875878758887589875908759187592875938759487595875968759787598875998760087601876028760387604876058760687607876088760987610876118761287613876148761587616876178761887619876208762187622876238762487625876268762787628876298763087631876328763387634876358763687637876388763987640876418764287643876448764587646876478764887649876508765187652876538765487655876568765787658876598766087661876628766387664876658766687667876688766987670876718767287673876748767587676876778767887679876808768187682876838768487685876868768787688876898769087691876928769387694876958769687697876988769987700877018770287703877048770587706877078770887709877108771187712877138771487715877168771787718877198772087721877228772387724877258772687727877288772987730877318773287733877348773587736877378773887739877408774187742877438774487745877468774787748877498775087751877528775387754877558775687757877588775987760877618776287763877648776587766877678776887769877708777187772877738777487775877768777787778877798778087781877828778387784877858778687787877888778987790877918779287793877948779587796877978779887799878008780187802878038780487805878068780787808878098781087811878128781387814878158781687817878188781987820878218782287823878248782587826878278782887829878308783187832878338783487835878368783787838878398784087841878428784387844878458784687847878488784987850878518785287853878548785587856878578785887859878608786187862878638786487865878668786787868878698787087871878728787387874878758787687877878788787987880878818788287883878848788587886878878788887889878908789187892878938789487895878968789787898878998790087901879028790387904879058790687907879088790987910879118791287913879148791587916879178791887919879208792187922879238792487925879268792787928879298793087931879328793387934879358793687937879388793987940879418794287943879448794587946879478794887949879508795187952879538795487955879568795787958879598796087961879628796387964879658796687967879688796987970879718797287973879748797587976879778797887979879808798187982879838798487985879868798787988879898799087991879928799387994879958799687997879988799988000880018800288003880048800588006880078800888009880108801188012880138801488015880168801788018880198802088021880228802388024880258802688027880288802988030880318803288033880348803588036880378803888039880408804188042880438804488045880468804788048880498805088051880528805388054880558805688057880588805988060880618806288063880648806588066880678806888069880708807188072880738807488075880768807788078880798808088081880828808388084880858808688087880888808988090880918809288093880948809588096880978809888099881008810188102881038810488105881068810788108881098811088111881128811388114881158811688117881188811988120881218812288123881248812588126881278812888129881308813188132881338813488135881368813788138881398814088141881428814388144881458814688147881488814988150881518815288153881548815588156881578815888159881608816188162881638816488165881668816788168881698817088171881728817388174881758817688177881788817988180881818818288183881848818588186881878818888189881908819188192881938819488195881968819788198881998820088201882028820388204882058820688207882088820988210882118821288213882148821588216882178821888219882208822188222882238822488225882268822788228882298823088231882328823388234882358823688237882388823988240882418824288243882448824588246882478824888249882508825188252882538825488255882568825788258882598826088261882628826388264882658826688267882688826988270882718827288273882748827588276882778827888279882808828188282882838828488285882868828788288882898829088291882928829388294882958829688297882988829988300883018830288303883048830588306883078830888309883108831188312883138831488315883168831788318883198832088321883228832388324883258832688327883288832988330883318833288333883348833588336883378833888339883408834188342883438834488345883468834788348883498835088351883528835388354883558835688357883588835988360883618836288363883648836588366883678836888369883708837188372883738837488375883768837788378883798838088381883828838388384883858838688387883888838988390883918839288393883948839588396883978839888399884008840188402884038840488405884068840788408884098841088411884128841388414884158841688417884188841988420884218842288423884248842588426884278842888429884308843188432884338843488435884368843788438884398844088441884428844388444884458844688447884488844988450884518845288453884548845588456884578845888459884608846188462884638846488465884668846788468884698847088471884728847388474884758847688477884788847988480884818848288483884848848588486884878848888489884908849188492884938849488495884968849788498884998850088501885028850388504885058850688507885088850988510885118851288513885148851588516885178851888519885208852188522885238852488525885268852788528885298853088531885328853388534885358853688537885388853988540885418854288543885448854588546885478854888549885508855188552885538855488555885568855788558885598856088561885628856388564885658856688567885688856988570885718857288573885748857588576885778857888579885808858188582885838858488585885868858788588885898859088591885928859388594885958859688597885988859988600886018860288603886048860588606886078860888609886108861188612886138861488615886168861788618886198862088621886228862388624886258862688627886288862988630886318863288633886348863588636886378863888639886408864188642886438864488645886468864788648886498865088651886528865388654886558865688657886588865988660886618866288663886648866588666886678866888669886708867188672886738867488675886768867788678886798868088681886828868388684886858868688687886888868988690886918869288693886948869588696886978869888699887008870188702887038870488705887068870788708887098871088711887128871388714887158871688717887188871988720887218872288723887248872588726887278872888729887308873188732887338873488735887368873788738887398874088741887428874388744887458874688747887488874988750887518875288753887548875588756887578875888759887608876188762887638876488765887668876788768887698877088771887728877388774887758877688777887788877988780887818878288783887848878588786887878878888789887908879188792887938879488795887968879788798887998880088801888028880388804888058880688807888088880988810888118881288813888148881588816888178881888819888208882188822888238882488825888268882788828888298883088831888328883388834888358883688837888388883988840888418884288843888448884588846888478884888849888508885188852888538885488855888568885788858888598886088861888628886388864888658886688867888688886988870888718887288873888748887588876888778887888879888808888188882888838888488885888868888788888888898889088891888928889388894888958889688897888988889988900889018890288903889048890588906889078890888909889108891188912889138891488915889168891788918889198892088921889228892388924889258892688927889288892988930889318893288933889348893588936889378893888939889408894188942889438894488945889468894788948889498895088951889528895388954889558895688957889588895988960889618896288963889648896588966889678896888969889708897188972889738897488975889768897788978889798898088981889828898388984889858898688987889888898988990889918899288993889948899588996889978899888999890008900189002890038900489005890068900789008890098901089011890128901389014890158901689017890188901989020890218902289023890248902589026890278902889029890308903189032890338903489035890368903789038890398904089041890428904389044890458904689047890488904989050890518905289053890548905589056890578905889059890608906189062890638906489065890668906789068890698907089071890728907389074890758907689077890788907989080890818908289083890848908589086890878908889089890908909189092890938909489095890968909789098890998910089101891028910389104891058910689107891088910989110891118911289113891148911589116891178911889119891208912189122891238912489125891268912789128891298913089131891328913389134891358913689137891388913989140891418914289143891448914589146891478914889149891508915189152891538915489155891568915789158891598916089161891628916389164891658916689167891688916989170891718917289173891748917589176891778917889179891808918189182891838918489185891868918789188891898919089191891928919389194891958919689197891988919989200892018920289203892048920589206892078920889209892108921189212892138921489215892168921789218892198922089221892228922389224892258922689227892288922989230892318923289233892348923589236892378923889239892408924189242892438924489245892468924789248892498925089251892528925389254892558925689257892588925989260892618926289263892648926589266892678926889269892708927189272892738927489275892768927789278892798928089281892828928389284892858928689287892888928989290892918929289293892948929589296892978929889299893008930189302893038930489305893068930789308893098931089311893128931389314893158931689317893188931989320893218932289323893248932589326893278932889329893308933189332893338933489335893368933789338893398934089341893428934389344893458934689347893488934989350893518935289353893548935589356893578935889359893608936189362893638936489365893668936789368893698937089371893728937389374893758937689377893788937989380893818938289383893848938589386893878938889389893908939189392893938939489395893968939789398893998940089401894028940389404894058940689407894088940989410894118941289413894148941589416894178941889419894208942189422894238942489425894268942789428894298943089431894328943389434894358943689437894388943989440894418944289443894448944589446894478944889449894508945189452894538945489455894568945789458894598946089461894628946389464894658946689467894688946989470894718947289473894748947589476894778947889479894808948189482894838948489485894868948789488894898949089491894928949389494894958949689497894988949989500895018950289503895048950589506895078950889509895108951189512895138951489515895168951789518895198952089521895228952389524895258952689527895288952989530895318953289533895348953589536895378953889539895408954189542895438954489545895468954789548895498955089551895528955389554895558955689557895588955989560895618956289563895648956589566895678956889569895708957189572895738957489575895768957789578895798958089581895828958389584895858958689587895888958989590895918959289593895948959589596895978959889599896008960189602896038960489605896068960789608896098961089611896128961389614896158961689617896188961989620896218962289623896248962589626896278962889629896308963189632896338963489635896368963789638896398964089641896428964389644896458964689647896488964989650896518965289653896548965589656896578965889659896608966189662896638966489665896668966789668896698967089671896728967389674896758967689677896788967989680896818968289683896848968589686896878968889689896908969189692896938969489695896968969789698896998970089701897028970389704897058970689707897088970989710897118971289713897148971589716897178971889719897208972189722897238972489725897268972789728897298973089731897328973389734897358973689737897388973989740897418974289743897448974589746897478974889749897508975189752897538975489755897568975789758897598976089761897628976389764897658976689767897688976989770897718977289773897748977589776897778977889779897808978189782897838978489785897868978789788897898979089791897928979389794897958979689797897988979989800898018980289803898048980589806898078980889809898108981189812898138981489815898168981789818898198982089821898228982389824898258982689827898288982989830898318983289833898348983589836898378983889839898408984189842898438984489845898468984789848898498985089851898528985389854898558985689857898588985989860898618986289863898648986589866898678986889869898708987189872898738987489875898768987789878898798988089881898828988389884898858988689887898888988989890898918989289893898948989589896898978989889899899008990189902899038990489905899068990789908899098991089911899128991389914899158991689917899188991989920899218992289923899248992589926899278992889929899308993189932899338993489935899368993789938899398994089941899428994389944899458994689947899488994989950899518995289953899548995589956899578995889959899608996189962899638996489965899668996789968899698997089971899728997389974899758997689977899788997989980899818998289983899848998589986899878998889989899908999189992899938999489995899968999789998899999000090001900029000390004900059000690007900089000990010900119001290013900149001590016900179001890019900209002190022900239002490025900269002790028900299003090031900329003390034900359003690037900389003990040900419004290043900449004590046900479004890049900509005190052900539005490055900569005790058900599006090061900629006390064900659006690067900689006990070900719007290073900749007590076900779007890079900809008190082900839008490085900869008790088900899009090091900929009390094900959009690097900989009990100901019010290103901049010590106901079010890109901109011190112901139011490115901169011790118901199012090121901229012390124901259012690127901289012990130901319013290133901349013590136901379013890139901409014190142901439014490145901469014790148901499015090151901529015390154901559015690157901589015990160901619016290163901649016590166901679016890169901709017190172901739017490175901769017790178901799018090181901829018390184901859018690187901889018990190901919019290193901949019590196901979019890199902009020190202902039020490205902069020790208902099021090211902129021390214902159021690217902189021990220902219022290223902249022590226902279022890229902309023190232902339023490235902369023790238902399024090241902429024390244902459024690247902489024990250902519025290253902549025590256902579025890259902609026190262902639026490265902669026790268902699027090271902729027390274902759027690277902789027990280902819028290283902849028590286902879028890289902909029190292902939029490295902969029790298902999030090301903029030390304903059030690307903089030990310903119031290313903149031590316903179031890319903209032190322903239032490325903269032790328903299033090331903329033390334903359033690337903389033990340903419034290343903449034590346903479034890349903509035190352903539035490355903569035790358903599036090361903629036390364903659036690367903689036990370903719037290373903749037590376903779037890379903809038190382903839038490385903869038790388903899039090391903929039390394903959039690397903989039990400904019040290403904049040590406904079040890409904109041190412904139041490415904169041790418904199042090421904229042390424904259042690427904289042990430904319043290433904349043590436904379043890439904409044190442904439044490445904469044790448904499045090451904529045390454904559045690457904589045990460904619046290463904649046590466904679046890469904709047190472904739047490475904769047790478904799048090481904829048390484904859048690487904889048990490904919049290493904949049590496904979049890499905009050190502905039050490505905069050790508905099051090511905129051390514905159051690517905189051990520905219052290523905249052590526905279052890529905309053190532905339053490535905369053790538905399054090541905429054390544905459054690547905489054990550905519055290553905549055590556905579055890559905609056190562905639056490565905669056790568905699057090571905729057390574905759057690577905789057990580905819058290583905849058590586905879058890589905909059190592905939059490595905969059790598905999060090601906029060390604906059060690607906089060990610906119061290613906149061590616906179061890619906209062190622906239062490625906269062790628906299063090631906329063390634906359063690637906389063990640906419064290643906449064590646906479064890649906509065190652906539065490655906569065790658906599066090661906629066390664906659066690667906689066990670906719067290673906749067590676906779067890679906809068190682906839068490685906869068790688906899069090691906929069390694906959069690697906989069990700907019070290703907049070590706907079070890709907109071190712907139071490715907169071790718907199072090721907229072390724907259072690727907289072990730907319073290733907349073590736907379073890739907409074190742907439074490745907469074790748907499075090751907529075390754907559075690757907589075990760907619076290763907649076590766907679076890769907709077190772907739077490775907769077790778907799078090781907829078390784907859078690787907889078990790907919079290793907949079590796907979079890799908009080190802908039080490805908069080790808908099081090811908129081390814908159081690817908189081990820908219082290823908249082590826908279082890829908309083190832908339083490835908369083790838908399084090841908429084390844908459084690847908489084990850908519085290853908549085590856908579085890859908609086190862908639086490865908669086790868908699087090871908729087390874908759087690877908789087990880908819088290883908849088590886908879088890889908909089190892908939089490895908969089790898908999090090901909029090390904909059090690907909089090990910909119091290913909149091590916909179091890919909209092190922909239092490925909269092790928909299093090931909329093390934909359093690937909389093990940909419094290943909449094590946909479094890949909509095190952909539095490955909569095790958909599096090961909629096390964909659096690967909689096990970909719097290973909749097590976909779097890979909809098190982909839098490985909869098790988909899099090991909929099390994909959099690997909989099991000910019100291003910049100591006910079100891009910109101191012910139101491015910169101791018910199102091021910229102391024910259102691027910289102991030910319103291033910349103591036910379103891039910409104191042910439104491045910469104791048910499105091051910529105391054910559105691057910589105991060910619106291063910649106591066910679106891069910709107191072910739107491075910769107791078910799108091081910829108391084910859108691087910889108991090910919109291093910949109591096910979109891099911009110191102911039110491105911069110791108911099111091111911129111391114911159111691117911189111991120911219112291123911249112591126911279112891129911309113191132911339113491135911369113791138911399114091141911429114391144911459114691147911489114991150911519115291153911549115591156911579115891159911609116191162911639116491165911669116791168911699117091171911729117391174911759117691177911789117991180911819118291183911849118591186911879118891189911909119191192911939119491195911969119791198911999120091201912029120391204912059120691207912089120991210912119121291213912149121591216912179121891219912209122191222912239122491225912269122791228912299123091231912329123391234912359123691237912389123991240912419124291243912449124591246912479124891249912509125191252912539125491255912569125791258912599126091261912629126391264912659126691267912689126991270912719127291273912749127591276912779127891279912809128191282912839128491285912869128791288912899129091291912929129391294912959129691297912989129991300913019130291303913049130591306913079130891309913109131191312913139131491315913169131791318913199132091321913229132391324913259132691327913289132991330913319133291333913349133591336913379133891339913409134191342913439134491345913469134791348913499135091351913529135391354913559135691357913589135991360913619136291363913649136591366913679136891369913709137191372913739137491375913769137791378913799138091381913829138391384913859138691387913889138991390913919139291393913949139591396913979139891399914009140191402914039140491405914069140791408914099141091411914129141391414914159141691417914189141991420914219142291423914249142591426914279142891429914309143191432914339143491435914369143791438914399144091441914429144391444914459144691447914489144991450914519145291453914549145591456914579145891459914609146191462914639146491465914669146791468914699147091471914729147391474914759147691477914789147991480914819148291483914849148591486914879148891489914909149191492914939149491495914969149791498914999150091501915029150391504915059150691507915089150991510915119151291513915149151591516915179151891519915209152191522915239152491525915269152791528915299153091531915329153391534915359153691537915389153991540915419154291543915449154591546915479154891549915509155191552915539155491555915569155791558915599156091561915629156391564915659156691567915689156991570915719157291573915749157591576915779157891579915809158191582915839158491585915869158791588915899159091591915929159391594915959159691597915989159991600916019160291603916049160591606916079160891609916109161191612916139161491615916169161791618916199162091621916229162391624916259162691627916289162991630916319163291633916349163591636916379163891639916409164191642916439164491645916469164791648916499165091651916529165391654916559165691657916589165991660916619166291663916649166591666916679166891669916709167191672916739167491675916769167791678916799168091681916829168391684916859168691687916889168991690916919169291693916949169591696916979169891699917009170191702917039170491705917069170791708917099171091711917129171391714917159171691717917189171991720917219172291723917249172591726917279172891729917309173191732917339173491735917369173791738917399174091741917429174391744917459174691747917489174991750917519175291753917549175591756917579175891759917609176191762917639176491765917669176791768917699177091771917729177391774917759177691777917789177991780917819178291783917849178591786917879178891789917909179191792917939179491795917969179791798917999180091801918029180391804918059180691807918089180991810918119181291813918149181591816918179181891819918209182191822918239182491825918269182791828918299183091831918329183391834918359183691837918389183991840918419184291843918449184591846918479184891849918509185191852918539185491855918569185791858918599186091861918629186391864918659186691867918689186991870918719187291873918749187591876918779187891879918809188191882918839188491885918869188791888918899189091891918929189391894918959189691897918989189991900919019190291903919049190591906919079190891909919109191191912919139191491915919169191791918919199192091921919229192391924919259192691927919289192991930919319193291933919349193591936919379193891939919409194191942919439194491945919469194791948919499195091951919529195391954919559195691957919589195991960919619196291963919649196591966919679196891969919709197191972919739197491975919769197791978919799198091981919829198391984919859198691987919889198991990919919199291993919949199591996919979199891999920009200192002920039200492005920069200792008920099201092011920129201392014920159201692017920189201992020920219202292023920249202592026920279202892029920309203192032920339203492035920369203792038920399204092041920429204392044920459204692047920489204992050920519205292053920549205592056920579205892059920609206192062920639206492065920669206792068920699207092071920729207392074920759207692077920789207992080920819208292083920849208592086920879208892089920909209192092920939209492095920969209792098920999210092101921029210392104921059210692107921089210992110921119211292113921149211592116921179211892119921209212192122921239212492125921269212792128921299213092131921329213392134921359213692137921389213992140921419214292143921449214592146921479214892149921509215192152921539215492155921569215792158921599216092161921629216392164921659216692167921689216992170921719217292173921749217592176921779217892179921809218192182921839218492185921869218792188921899219092191921929219392194921959219692197921989219992200922019220292203922049220592206922079220892209922109221192212922139221492215922169221792218922199222092221922229222392224922259222692227922289222992230922319223292233922349223592236922379223892239922409224192242922439224492245922469224792248922499225092251922529225392254922559225692257922589225992260922619226292263922649226592266922679226892269922709227192272922739227492275922769227792278922799228092281922829228392284922859228692287922889228992290922919229292293922949229592296922979229892299923009230192302923039230492305923069230792308923099231092311923129231392314923159231692317923189231992320923219232292323923249232592326923279232892329923309233192332923339233492335923369233792338923399234092341923429234392344923459234692347923489234992350923519235292353923549235592356923579235892359923609236192362923639236492365923669236792368923699237092371923729237392374923759237692377923789237992380923819238292383923849238592386923879238892389923909239192392923939239492395923969239792398923999240092401924029240392404924059240692407924089240992410924119241292413924149241592416924179241892419924209242192422924239242492425924269242792428924299243092431924329243392434924359243692437924389243992440924419244292443924449244592446924479244892449924509245192452924539245492455924569245792458924599246092461924629246392464924659246692467924689246992470924719247292473924749247592476924779247892479924809248192482924839248492485924869248792488924899249092491924929249392494924959249692497924989249992500925019250292503925049250592506925079250892509925109251192512925139251492515925169251792518925199252092521925229252392524925259252692527925289252992530925319253292533925349253592536925379253892539925409254192542925439254492545925469254792548925499255092551925529255392554925559255692557925589255992560925619256292563925649256592566925679256892569925709257192572925739257492575925769257792578925799258092581925829258392584925859258692587925889258992590925919259292593925949259592596925979259892599926009260192602926039260492605926069260792608926099261092611926129261392614926159261692617926189261992620926219262292623926249262592626926279262892629926309263192632926339263492635926369263792638926399264092641926429264392644926459264692647926489264992650926519265292653926549265592656926579265892659926609266192662926639266492665926669266792668926699267092671926729267392674926759267692677926789267992680926819268292683926849268592686926879268892689926909269192692926939269492695926969269792698926999270092701927029270392704927059270692707927089270992710927119271292713927149271592716927179271892719927209272192722927239272492725927269272792728927299273092731927329273392734927359273692737927389273992740927419274292743927449274592746927479274892749927509275192752927539275492755927569275792758927599276092761927629276392764927659276692767927689276992770927719277292773927749277592776927779277892779927809278192782927839278492785927869278792788927899279092791927929279392794927959279692797927989279992800928019280292803928049280592806928079280892809928109281192812928139281492815928169281792818928199282092821928229282392824928259282692827928289282992830928319283292833928349283592836928379283892839928409284192842928439284492845928469284792848928499285092851928529285392854928559285692857928589285992860928619286292863928649286592866928679286892869928709287192872928739287492875928769287792878928799288092881928829288392884928859288692887928889288992890928919289292893928949289592896928979289892899929009290192902929039290492905929069290792908929099291092911929129291392914929159291692917929189291992920929219292292923929249292592926929279292892929929309293192932929339293492935929369293792938929399294092941929429294392944929459294692947929489294992950929519295292953929549295592956929579295892959929609296192962929639296492965929669296792968929699297092971929729297392974929759297692977929789297992980929819298292983929849298592986929879298892989929909299192992929939299492995929969299792998929999300093001930029300393004930059300693007930089300993010930119301293013930149301593016930179301893019930209302193022930239302493025930269302793028930299303093031930329303393034930359303693037930389303993040930419304293043930449304593046930479304893049930509305193052930539305493055930569305793058930599306093061930629306393064930659306693067930689306993070930719307293073930749307593076930779307893079930809308193082930839308493085930869308793088930899309093091930929309393094930959309693097930989309993100931019310293103931049310593106931079310893109931109311193112931139311493115931169311793118931199312093121931229312393124931259312693127931289312993130931319313293133931349313593136931379313893139931409314193142931439314493145931469314793148931499315093151931529315393154931559315693157931589315993160931619316293163931649316593166931679316893169931709317193172931739317493175931769317793178931799318093181931829318393184931859318693187931889318993190931919319293193931949319593196931979319893199932009320193202932039320493205932069320793208932099321093211932129321393214932159321693217932189321993220932219322293223932249322593226932279322893229932309323193232932339323493235932369323793238932399324093241932429324393244932459324693247932489324993250932519325293253932549325593256932579325893259932609326193262932639326493265932669326793268932699327093271932729327393274932759327693277932789327993280932819328293283932849328593286932879328893289932909329193292932939329493295932969329793298932999330093301933029330393304933059330693307933089330993310933119331293313933149331593316933179331893319933209332193322933239332493325933269332793328933299333093331933329333393334933359333693337933389333993340933419334293343933449334593346933479334893349933509335193352933539335493355933569335793358933599336093361933629336393364933659336693367933689336993370933719337293373933749337593376933779337893379933809338193382933839338493385933869338793388933899339093391933929339393394933959339693397933989339993400934019340293403934049340593406934079340893409934109341193412934139341493415934169341793418934199342093421934229342393424934259342693427934289342993430934319343293433934349343593436934379343893439934409344193442934439344493445934469344793448934499345093451934529345393454934559345693457934589345993460934619346293463934649346593466934679346893469934709347193472934739347493475934769347793478934799348093481934829348393484934859348693487934889348993490934919349293493934949349593496934979349893499935009350193502935039350493505935069350793508935099351093511935129351393514935159351693517935189351993520935219352293523935249352593526935279352893529935309353193532935339353493535935369353793538935399354093541935429354393544935459354693547935489354993550935519355293553935549355593556935579355893559935609356193562935639356493565935669356793568935699357093571935729357393574935759357693577935789357993580935819358293583935849358593586935879358893589935909359193592935939359493595935969359793598935999360093601936029360393604936059360693607936089360993610936119361293613936149361593616936179361893619936209362193622936239362493625936269362793628936299363093631936329363393634936359363693637936389363993640936419364293643936449364593646936479364893649936509365193652936539365493655936569365793658936599366093661936629366393664936659366693667936689366993670936719367293673936749367593676936779367893679936809368193682936839368493685936869368793688936899369093691936929369393694936959369693697936989369993700937019370293703937049370593706937079370893709937109371193712937139371493715937169371793718937199372093721937229372393724937259372693727937289372993730937319373293733937349373593736937379373893739937409374193742937439374493745937469374793748937499375093751937529375393754937559375693757937589375993760937619376293763937649376593766937679376893769937709377193772937739377493775937769377793778937799378093781937829378393784937859378693787937889378993790937919379293793937949379593796937979379893799938009380193802938039380493805938069380793808938099381093811938129381393814938159381693817938189381993820938219382293823938249382593826938279382893829938309383193832938339383493835938369383793838938399384093841938429384393844938459384693847938489384993850938519385293853938549385593856938579385893859938609386193862938639386493865938669386793868938699387093871938729387393874938759387693877938789387993880938819388293883938849388593886938879388893889938909389193892938939389493895938969389793898938999390093901939029390393904939059390693907939089390993910939119391293913939149391593916939179391893919939209392193922939239392493925939269392793928939299393093931939329393393934939359393693937939389393993940939419394293943939449394593946939479394893949939509395193952939539395493955939569395793958939599396093961939629396393964939659396693967939689396993970939719397293973939749397593976939779397893979939809398193982939839398493985939869398793988939899399093991939929399393994939959399693997939989399994000940019400294003940049400594006940079400894009940109401194012940139401494015940169401794018940199402094021940229402394024940259402694027940289402994030940319403294033940349403594036940379403894039940409404194042940439404494045940469404794048940499405094051940529405394054940559405694057940589405994060940619406294063940649406594066940679406894069940709407194072940739407494075940769407794078940799408094081940829408394084940859408694087940889408994090940919409294093940949409594096940979409894099941009410194102941039410494105941069410794108941099411094111941129411394114941159411694117941189411994120941219412294123941249412594126941279412894129941309413194132941339413494135941369413794138941399414094141941429414394144941459414694147941489414994150941519415294153941549415594156941579415894159941609416194162941639416494165941669416794168941699417094171941729417394174941759417694177941789417994180941819418294183941849418594186941879418894189941909419194192941939419494195941969419794198941999420094201942029420394204942059420694207942089420994210942119421294213942149421594216942179421894219942209422194222942239422494225942269422794228942299423094231942329423394234942359423694237942389423994240942419424294243942449424594246942479424894249942509425194252942539425494255942569425794258942599426094261942629426394264942659426694267942689426994270942719427294273942749427594276942779427894279942809428194282942839428494285942869428794288942899429094291942929429394294942959429694297942989429994300943019430294303943049430594306943079430894309943109431194312943139431494315943169431794318943199432094321943229432394324943259432694327943289432994330943319433294333943349433594336943379433894339943409434194342943439434494345943469434794348943499435094351943529435394354943559435694357943589435994360943619436294363943649436594366943679436894369943709437194372943739437494375943769437794378943799438094381943829438394384943859438694387943889438994390943919439294393943949439594396943979439894399944009440194402944039440494405944069440794408944099441094411944129441394414944159441694417944189441994420944219442294423944249442594426944279442894429944309443194432944339443494435944369443794438944399444094441944429444394444944459444694447944489444994450944519445294453944549445594456944579445894459944609446194462944639446494465944669446794468944699447094471944729447394474944759447694477944789447994480944819448294483944849448594486944879448894489944909449194492944939449494495944969449794498944999450094501945029450394504945059450694507945089450994510945119451294513945149451594516945179451894519945209452194522945239452494525945269452794528945299453094531945329453394534945359453694537945389453994540945419454294543945449454594546945479454894549945509455194552945539455494555945569455794558945599456094561945629456394564945659456694567945689456994570945719457294573945749457594576945779457894579945809458194582945839458494585945869458794588945899459094591945929459394594945959459694597945989459994600946019460294603946049460594606946079460894609946109461194612946139461494615946169461794618946199462094621946229462394624946259462694627946289462994630946319463294633946349463594636946379463894639946409464194642946439464494645946469464794648946499465094651946529465394654946559465694657946589465994660946619466294663946649466594666946679466894669946709467194672946739467494675946769467794678946799468094681946829468394684946859468694687946889468994690946919469294693946949469594696946979469894699947009470194702947039470494705947069470794708947099471094711947129471394714947159471694717947189471994720947219472294723947249472594726947279472894729947309473194732947339473494735947369473794738947399474094741947429474394744947459474694747947489474994750947519475294753947549475594756947579475894759947609476194762947639476494765947669476794768947699477094771947729477394774947759477694777947789477994780947819478294783947849478594786947879478894789947909479194792947939479494795947969479794798947999480094801948029480394804948059480694807948089480994810948119481294813948149481594816948179481894819948209482194822948239482494825948269482794828948299483094831948329483394834948359483694837948389483994840948419484294843948449484594846948479484894849948509485194852948539485494855948569485794858948599486094861948629486394864948659486694867948689486994870948719487294873948749487594876948779487894879948809488194882948839488494885948869488794888948899489094891948929489394894948959489694897948989489994900949019490294903949049490594906949079490894909949109491194912949139491494915949169491794918949199492094921949229492394924949259492694927949289492994930949319493294933949349493594936949379493894939949409494194942949439494494945949469494794948949499495094951949529495394954949559495694957949589495994960949619496294963949649496594966949679496894969949709497194972949739497494975949769497794978949799498094981949829498394984949859498694987949889498994990949919499294993949949499594996949979499894999950009500195002950039500495005950069500795008950099501095011950129501395014950159501695017950189501995020950219502295023950249502595026950279502895029950309503195032950339503495035950369503795038950399504095041950429504395044950459504695047950489504995050950519505295053950549505595056950579505895059950609506195062950639506495065950669506795068950699507095071950729507395074950759507695077950789507995080950819508295083950849508595086950879508895089950909509195092950939509495095950969509795098950999510095101951029510395104951059510695107951089510995110951119511295113951149511595116951179511895119951209512195122951239512495125951269512795128951299513095131951329513395134951359513695137951389513995140951419514295143951449514595146951479514895149951509515195152951539515495155951569515795158951599516095161951629516395164951659516695167951689516995170951719517295173951749517595176951779517895179951809518195182951839518495185951869518795188951899519095191951929519395194951959519695197951989519995200952019520295203952049520595206952079520895209952109521195212952139521495215952169521795218952199522095221952229522395224952259522695227952289522995230952319523295233952349523595236952379523895239952409524195242952439524495245952469524795248952499525095251952529525395254952559525695257952589525995260952619526295263952649526595266952679526895269952709527195272952739527495275952769527795278952799528095281952829528395284952859528695287952889528995290952919529295293952949529595296952979529895299953009530195302953039530495305953069530795308953099531095311953129531395314953159531695317953189531995320953219532295323953249532595326953279532895329953309533195332953339533495335953369533795338953399534095341953429534395344953459534695347953489534995350953519535295353953549535595356953579535895359953609536195362953639536495365953669536795368953699537095371953729537395374953759537695377953789537995380953819538295383953849538595386953879538895389953909539195392953939539495395953969539795398953999540095401954029540395404954059540695407954089540995410954119541295413954149541595416954179541895419954209542195422954239542495425954269542795428954299543095431954329543395434954359543695437954389543995440954419544295443954449544595446954479544895449954509545195452954539545495455954569545795458954599546095461954629546395464954659546695467954689546995470954719547295473954749547595476954779547895479954809548195482954839548495485954869548795488954899549095491954929549395494954959549695497954989549995500955019550295503955049550595506955079550895509955109551195512955139551495515955169551795518955199552095521955229552395524955259552695527955289552995530955319553295533955349553595536955379553895539955409554195542955439554495545955469554795548955499555095551955529555395554955559555695557955589555995560955619556295563955649556595566955679556895569955709557195572955739557495575955769557795578955799558095581955829558395584955859558695587955889558995590955919559295593955949559595596955979559895599956009560195602956039560495605956069560795608956099561095611956129561395614956159561695617956189561995620956219562295623956249562595626956279562895629
  1. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  2. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  3. (function universalModuleDefinition(root, factory) {
  4. var amdDependencies = [];
  5. var CANNON = root.CANNON || this.CANNON;
  6. var OIMO = root.OIMO || this.OIMO;
  7. var earcut = root.earcut || this.earcut;
  8. if(typeof exports === 'object' && typeof module === 'object') {
  9. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  10. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  11. try { earcut = earcut || require("earcut"); } catch(e) {}
  12. module.exports = factory(CANNON,OIMO,earcut);
  13. } else if(typeof define === 'function' && define.amd) {
  14. if(require.specified && require.specified("cannon")) amdDependencies.push("cannon");
  15. if(require.specified && require.specified("oimo")) amdDependencies.push("oimo");
  16. if(require.specified && require.specified("earcut")) amdDependencies.push("earcut");
  17. define("babylonjs", amdDependencies, factory);
  18. } else if(typeof exports === 'object') {
  19. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  20. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  21. try { earcut = earcut || require("earcut"); } catch(e) {}
  22. exports["babylonjs"] = factory(CANNON,OIMO,earcut);
  23. } else {
  24. root["BABYLON"] = factory(CANNON,OIMO,earcut);
  25. }
  26. })(this, function(CANNON,OIMO,earcut) {
  27. CANNON = CANNON || this.CANNON;
  28. OIMO = OIMO || this.OIMO;
  29. earcut = earcut || this.earcut;
  30. "use strict";
  31. var BABYLON;
  32. (function (BABYLON) {
  33. /**
  34. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  35. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  36. */
  37. var EffectFallbacks = /** @class */ (function () {
  38. function EffectFallbacks() {
  39. this._defines = {};
  40. this._currentRank = 32;
  41. this._maxRank = -1;
  42. }
  43. /**
  44. * Removes the fallback from the bound mesh.
  45. */
  46. EffectFallbacks.prototype.unBindMesh = function () {
  47. this._mesh = null;
  48. };
  49. /**
  50. * Adds a fallback on the specified property.
  51. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  52. * @param define The name of the define in the shader
  53. */
  54. EffectFallbacks.prototype.addFallback = function (rank, define) {
  55. if (!this._defines[rank]) {
  56. if (rank < this._currentRank) {
  57. this._currentRank = rank;
  58. }
  59. if (rank > this._maxRank) {
  60. this._maxRank = rank;
  61. }
  62. this._defines[rank] = new Array();
  63. }
  64. this._defines[rank].push(define);
  65. };
  66. /**
  67. * Sets the mesh to use CPU skinning when needing to fallback.
  68. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  69. * @param mesh The mesh to use the fallbacks.
  70. */
  71. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  72. this._mesh = mesh;
  73. if (rank < this._currentRank) {
  74. this._currentRank = rank;
  75. }
  76. if (rank > this._maxRank) {
  77. this._maxRank = rank;
  78. }
  79. };
  80. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  81. /**
  82. * Checks to see if more fallbacks are still availible.
  83. */
  84. get: function () {
  85. return this._currentRank <= this._maxRank;
  86. },
  87. enumerable: true,
  88. configurable: true
  89. });
  90. /**
  91. * Removes the defines that shoould be removed when falling back.
  92. * @param currentDefines defines the current define statements for the shader.
  93. * @param effect defines the current effect we try to compile
  94. * @returns The resulting defines with defines of the current rank removed.
  95. */
  96. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  97. // First we try to switch to CPU skinning
  98. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  99. this._mesh.computeBonesUsingShaders = false;
  100. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  101. var scene = this._mesh.getScene();
  102. for (var index = 0; index < scene.meshes.length; index++) {
  103. var otherMesh = scene.meshes[index];
  104. if (!otherMesh.material) {
  105. continue;
  106. }
  107. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  108. continue;
  109. }
  110. if (otherMesh.material.getEffect() === effect) {
  111. otherMesh.computeBonesUsingShaders = false;
  112. }
  113. else {
  114. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  115. var subMesh = _a[_i];
  116. var subMeshEffect = subMesh.effect;
  117. if (subMeshEffect === effect) {
  118. otherMesh.computeBonesUsingShaders = false;
  119. break;
  120. }
  121. }
  122. }
  123. }
  124. }
  125. else {
  126. var currentFallbacks = this._defines[this._currentRank];
  127. if (currentFallbacks) {
  128. for (var index = 0; index < currentFallbacks.length; index++) {
  129. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  130. }
  131. }
  132. this._currentRank++;
  133. }
  134. return currentDefines;
  135. };
  136. return EffectFallbacks;
  137. }());
  138. BABYLON.EffectFallbacks = EffectFallbacks;
  139. /**
  140. * Options to be used when creating an effect.
  141. */
  142. var EffectCreationOptions = /** @class */ (function () {
  143. function EffectCreationOptions() {
  144. }
  145. return EffectCreationOptions;
  146. }());
  147. BABYLON.EffectCreationOptions = EffectCreationOptions;
  148. /**
  149. * Effect containing vertex and fragment shader that can be executed on an object.
  150. */
  151. var Effect = /** @class */ (function () {
  152. /**
  153. * Instantiates an effect.
  154. * An effect can be used to create/manage/execute vertex and fragment shaders.
  155. * @param baseName Name of the effect.
  156. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  157. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  158. * @param samplers List of sampler variables that will be passed to the shader.
  159. * @param engine Engine to be used to render the effect
  160. * @param defines Define statements to be added to the shader.
  161. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  162. * @param onCompiled Callback that will be called when the shader is compiled.
  163. * @param onError Callback that will be called if an error occurs during shader compilation.
  164. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  165. */
  166. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  167. if (samplers === void 0) { samplers = null; }
  168. if (defines === void 0) { defines = null; }
  169. if (fallbacks === void 0) { fallbacks = null; }
  170. if (onCompiled === void 0) { onCompiled = null; }
  171. if (onError === void 0) { onError = null; }
  172. var _this = this;
  173. /**
  174. * Unique ID of the effect.
  175. */
  176. this.uniqueId = 0;
  177. /**
  178. * Observable that will be called when the shader is compiled.
  179. */
  180. this.onCompileObservable = new BABYLON.Observable();
  181. /**
  182. * Observable that will be called if an error occurs during shader compilation.
  183. */
  184. this.onErrorObservable = new BABYLON.Observable();
  185. /**
  186. * Observable that will be called when effect is bound.
  187. */
  188. this.onBindObservable = new BABYLON.Observable();
  189. this._uniformBuffersNames = {};
  190. this._isReady = false;
  191. this._compilationError = "";
  192. this.name = baseName;
  193. if (attributesNamesOrOptions.attributes) {
  194. var options = attributesNamesOrOptions;
  195. this._engine = uniformsNamesOrEngine;
  196. this._attributesNames = options.attributes;
  197. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  198. this._samplers = options.samplers.slice();
  199. this.defines = options.defines;
  200. this.onError = options.onError;
  201. this.onCompiled = options.onCompiled;
  202. this._fallbacks = options.fallbacks;
  203. this._indexParameters = options.indexParameters;
  204. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  205. if (options.uniformBuffersNames) {
  206. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  207. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  208. }
  209. }
  210. }
  211. else {
  212. this._engine = engine;
  213. this.defines = defines;
  214. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  215. this._samplers = samplers ? samplers.slice() : [];
  216. this._attributesNames = attributesNamesOrOptions;
  217. this.onError = onError;
  218. this.onCompiled = onCompiled;
  219. this._indexParameters = indexParameters;
  220. this._fallbacks = fallbacks;
  221. }
  222. this.uniqueId = Effect._uniqueIdSeed++;
  223. var vertexSource;
  224. var fragmentSource;
  225. if (baseName.vertexElement) {
  226. vertexSource = document.getElementById(baseName.vertexElement);
  227. if (!vertexSource) {
  228. vertexSource = baseName.vertexElement;
  229. }
  230. }
  231. else {
  232. vertexSource = baseName.vertex || baseName;
  233. }
  234. if (baseName.fragmentElement) {
  235. fragmentSource = document.getElementById(baseName.fragmentElement);
  236. if (!fragmentSource) {
  237. fragmentSource = baseName.fragmentElement;
  238. }
  239. }
  240. else {
  241. fragmentSource = baseName.fragment || baseName;
  242. }
  243. this._loadVertexShader(vertexSource, function (vertexCode) {
  244. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  245. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  246. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  247. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  248. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  249. if (baseName) {
  250. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  251. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  252. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  253. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  254. }
  255. else {
  256. _this._vertexSourceCode = migratedVertexCode;
  257. _this._fragmentSourceCode = migratedFragmentCode;
  258. }
  259. _this._prepareEffect();
  260. });
  261. });
  262. });
  263. });
  264. });
  265. });
  266. }
  267. Object.defineProperty(Effect.prototype, "key", {
  268. /**
  269. * Unique key for this effect
  270. */
  271. get: function () {
  272. return this._key;
  273. },
  274. enumerable: true,
  275. configurable: true
  276. });
  277. /**
  278. * If the effect has been compiled and prepared.
  279. * @returns if the effect is compiled and prepared.
  280. */
  281. Effect.prototype.isReady = function () {
  282. return this._isReady;
  283. };
  284. /**
  285. * The engine the effect was initialized with.
  286. * @returns the engine.
  287. */
  288. Effect.prototype.getEngine = function () {
  289. return this._engine;
  290. };
  291. /**
  292. * The compiled webGL program for the effect
  293. * @returns the webGL program.
  294. */
  295. Effect.prototype.getProgram = function () {
  296. return this._program;
  297. };
  298. /**
  299. * The set of names of attribute variables for the shader.
  300. * @returns An array of attribute names.
  301. */
  302. Effect.prototype.getAttributesNames = function () {
  303. return this._attributesNames;
  304. };
  305. /**
  306. * Returns the attribute at the given index.
  307. * @param index The index of the attribute.
  308. * @returns The location of the attribute.
  309. */
  310. Effect.prototype.getAttributeLocation = function (index) {
  311. return this._attributes[index];
  312. };
  313. /**
  314. * Returns the attribute based on the name of the variable.
  315. * @param name of the attribute to look up.
  316. * @returns the attribute location.
  317. */
  318. Effect.prototype.getAttributeLocationByName = function (name) {
  319. var index = this._attributesNames.indexOf(name);
  320. return this._attributes[index];
  321. };
  322. /**
  323. * The number of attributes.
  324. * @returns the numnber of attributes.
  325. */
  326. Effect.prototype.getAttributesCount = function () {
  327. return this._attributes.length;
  328. };
  329. /**
  330. * Gets the index of a uniform variable.
  331. * @param uniformName of the uniform to look up.
  332. * @returns the index.
  333. */
  334. Effect.prototype.getUniformIndex = function (uniformName) {
  335. return this._uniformsNames.indexOf(uniformName);
  336. };
  337. /**
  338. * Returns the attribute based on the name of the variable.
  339. * @param uniformName of the uniform to look up.
  340. * @returns the location of the uniform.
  341. */
  342. Effect.prototype.getUniform = function (uniformName) {
  343. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  344. };
  345. /**
  346. * Returns an array of sampler variable names
  347. * @returns The array of sampler variable neames.
  348. */
  349. Effect.prototype.getSamplers = function () {
  350. return this._samplers;
  351. };
  352. /**
  353. * The error from the last compilation.
  354. * @returns the error string.
  355. */
  356. Effect.prototype.getCompilationError = function () {
  357. return this._compilationError;
  358. };
  359. /**
  360. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  361. * @param func The callback to be used.
  362. */
  363. Effect.prototype.executeWhenCompiled = function (func) {
  364. if (this.isReady()) {
  365. func(this);
  366. return;
  367. }
  368. this.onCompileObservable.add(function (effect) {
  369. func(effect);
  370. });
  371. };
  372. /** @ignore */
  373. Effect.prototype._loadVertexShader = function (vertex, callback) {
  374. if (BABYLON.Tools.IsWindowObjectExist()) {
  375. // DOM element ?
  376. if (vertex instanceof HTMLElement) {
  377. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  378. callback(vertexCode);
  379. return;
  380. }
  381. }
  382. // Base64 encoded ?
  383. if (vertex.substr(0, 7) === "base64:") {
  384. var vertexBinary = window.atob(vertex.substr(7));
  385. callback(vertexBinary);
  386. return;
  387. }
  388. // Is in local store ?
  389. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  390. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  391. return;
  392. }
  393. var vertexShaderUrl;
  394. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  395. vertexShaderUrl = vertex;
  396. }
  397. else {
  398. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  399. }
  400. // Vertex shader
  401. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  402. };
  403. /** @ignore */
  404. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  405. if (BABYLON.Tools.IsWindowObjectExist()) {
  406. // DOM element ?
  407. if (fragment instanceof HTMLElement) {
  408. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  409. callback(fragmentCode);
  410. return;
  411. }
  412. }
  413. // Base64 encoded ?
  414. if (fragment.substr(0, 7) === "base64:") {
  415. var fragmentBinary = window.atob(fragment.substr(7));
  416. callback(fragmentBinary);
  417. return;
  418. }
  419. // Is in local store ?
  420. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  421. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  422. return;
  423. }
  424. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  425. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  426. return;
  427. }
  428. var fragmentShaderUrl;
  429. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  430. fragmentShaderUrl = fragment;
  431. }
  432. else {
  433. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  434. }
  435. // Fragment shader
  436. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  437. };
  438. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  439. // Rebuild shaders source code
  440. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  441. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  442. vertexCode = prefix + vertexCode;
  443. fragmentCode = prefix + fragmentCode;
  444. // Number lines of shaders source code
  445. var i = 2;
  446. var regex = /\n/gm;
  447. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  448. i = 2;
  449. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  450. // Dump shaders name and formatted source code
  451. if (this.name.vertexElement) {
  452. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  453. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  454. }
  455. else if (this.name.vertex) {
  456. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  457. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  458. }
  459. else {
  460. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  461. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  462. }
  463. };
  464. ;
  465. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  466. var preparedSourceCode = this._processPrecision(sourceCode);
  467. if (this._engine.webGLVersion == 1) {
  468. callback(preparedSourceCode);
  469. return;
  470. }
  471. // Already converted
  472. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  473. callback(preparedSourceCode.replace("#version 300 es", ""));
  474. return;
  475. }
  476. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  477. // Remove extensions
  478. // #extension GL_OES_standard_derivatives : enable
  479. // #extension GL_EXT_shader_texture_lod : enable
  480. // #extension GL_EXT_frag_depth : enable
  481. // #extension GL_EXT_draw_buffers : require
  482. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  483. var result = preparedSourceCode.replace(regex, "");
  484. // Migrate to GLSL v300
  485. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  486. result = result.replace(/attribute[ \t]/g, "in ");
  487. result = result.replace(/[ \t]attribute/g, " in");
  488. if (isFragment) {
  489. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  490. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  491. result = result.replace(/texture2D\s*\(/g, "texture(");
  492. result = result.replace(/textureCube\s*\(/g, "texture(");
  493. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  494. result = result.replace(/gl_FragColor/g, "glFragColor");
  495. result = result.replace(/gl_FragData/g, "glFragData");
  496. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  497. }
  498. callback(result);
  499. };
  500. Effect.prototype._processIncludes = function (sourceCode, callback) {
  501. var _this = this;
  502. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  503. var match = regex.exec(sourceCode);
  504. var returnValue = new String(sourceCode);
  505. while (match != null) {
  506. var includeFile = match[1];
  507. // Uniform declaration
  508. if (includeFile.indexOf("__decl__") !== -1) {
  509. includeFile = includeFile.replace(/__decl__/, "");
  510. if (this._engine.supportsUniformBuffers) {
  511. includeFile = includeFile.replace(/Vertex/, "Ubo");
  512. includeFile = includeFile.replace(/Fragment/, "Ubo");
  513. }
  514. includeFile = includeFile + "Declaration";
  515. }
  516. if (Effect.IncludesShadersStore[includeFile]) {
  517. // Substitution
  518. var includeContent = Effect.IncludesShadersStore[includeFile];
  519. if (match[2]) {
  520. var splits = match[3].split(",");
  521. for (var index = 0; index < splits.length; index += 2) {
  522. var source = new RegExp(splits[index], "g");
  523. var dest = splits[index + 1];
  524. includeContent = includeContent.replace(source, dest);
  525. }
  526. }
  527. if (match[4]) {
  528. var indexString = match[5];
  529. if (indexString.indexOf("..") !== -1) {
  530. var indexSplits = indexString.split("..");
  531. var minIndex = parseInt(indexSplits[0]);
  532. var maxIndex = parseInt(indexSplits[1]);
  533. var sourceIncludeContent = includeContent.slice(0);
  534. includeContent = "";
  535. if (isNaN(maxIndex)) {
  536. maxIndex = this._indexParameters[indexSplits[1]];
  537. }
  538. for (var i = minIndex; i < maxIndex; i++) {
  539. if (!this._engine.supportsUniformBuffers) {
  540. // Ubo replacement
  541. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  542. return p1 + "{X}";
  543. });
  544. }
  545. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  546. }
  547. }
  548. else {
  549. if (!this._engine.supportsUniformBuffers) {
  550. // Ubo replacement
  551. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  552. return p1 + "{X}";
  553. });
  554. }
  555. includeContent = includeContent.replace(/\{X\}/g, indexString);
  556. }
  557. }
  558. // Replace
  559. returnValue = returnValue.replace(match[0], includeContent);
  560. }
  561. else {
  562. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  563. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  564. Effect.IncludesShadersStore[includeFile] = fileContent;
  565. _this._processIncludes(returnValue, callback);
  566. });
  567. return;
  568. }
  569. match = regex.exec(sourceCode);
  570. }
  571. callback(returnValue);
  572. };
  573. Effect.prototype._processPrecision = function (source) {
  574. if (source.indexOf("precision highp float") === -1) {
  575. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  576. source = "precision mediump float;\n" + source;
  577. }
  578. else {
  579. source = "precision highp float;\n" + source;
  580. }
  581. }
  582. else {
  583. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  584. source = source.replace("precision highp float", "precision mediump float");
  585. }
  586. }
  587. return source;
  588. };
  589. /**
  590. * Recompiles the webGL program
  591. * @param vertexSourceCode The source code for the vertex shader.
  592. * @param fragmentSourceCode The source code for the fragment shader.
  593. * @param onCompiled Callback called when completed.
  594. * @param onError Callback called on error.
  595. */
  596. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  597. var _this = this;
  598. this._isReady = false;
  599. this._vertexSourceCodeOverride = vertexSourceCode;
  600. this._fragmentSourceCodeOverride = fragmentSourceCode;
  601. this.onError = function (effect, error) {
  602. if (onError) {
  603. onError(error);
  604. }
  605. };
  606. this.onCompiled = function () {
  607. var scenes = _this.getEngine().scenes;
  608. for (var i = 0; i < scenes.length; i++) {
  609. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  610. }
  611. if (onCompiled) {
  612. onCompiled(_this._program);
  613. }
  614. };
  615. this._fallbacks = null;
  616. this._prepareEffect();
  617. };
  618. /**
  619. * Gets the uniform locations of the the specified variable names
  620. * @param names THe names of the variables to lookup.
  621. * @returns Array of locations in the same order as variable names.
  622. */
  623. Effect.prototype.getSpecificUniformLocations = function (names) {
  624. var engine = this._engine;
  625. return engine.getUniforms(this._program, names);
  626. };
  627. /**
  628. * Prepares the effect
  629. */
  630. Effect.prototype._prepareEffect = function () {
  631. var attributesNames = this._attributesNames;
  632. var defines = this.defines;
  633. var fallbacks = this._fallbacks;
  634. this._valueCache = {};
  635. var previousProgram = this._program;
  636. try {
  637. var engine = this._engine;
  638. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  639. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  640. }
  641. else {
  642. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  643. }
  644. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  645. if (engine.supportsUniformBuffers) {
  646. for (var name in this._uniformBuffersNames) {
  647. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  648. }
  649. }
  650. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  651. this._attributes = engine.getAttributes(this._program, attributesNames);
  652. var index;
  653. for (index = 0; index < this._samplers.length; index++) {
  654. var sampler = this.getUniform(this._samplers[index]);
  655. if (sampler == null) {
  656. this._samplers.splice(index, 1);
  657. index--;
  658. }
  659. }
  660. engine.bindSamplers(this);
  661. this._compilationError = "";
  662. this._isReady = true;
  663. if (this.onCompiled) {
  664. this.onCompiled(this);
  665. }
  666. this.onCompileObservable.notifyObservers(this);
  667. this.onCompileObservable.clear();
  668. // Unbind mesh reference in fallbacks
  669. if (this._fallbacks) {
  670. this._fallbacks.unBindMesh();
  671. }
  672. if (previousProgram) {
  673. this.getEngine()._deleteProgram(previousProgram);
  674. }
  675. }
  676. catch (e) {
  677. this._compilationError = e.message;
  678. // Let's go through fallbacks then
  679. BABYLON.Tools.Error("Unable to compile effect:");
  680. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  681. return " " + uniform;
  682. }));
  683. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  684. return " " + attribute;
  685. }));
  686. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  687. BABYLON.Tools.Error("Error: " + this._compilationError);
  688. if (previousProgram) {
  689. this._program = previousProgram;
  690. this._isReady = true;
  691. if (this.onError) {
  692. this.onError(this, this._compilationError);
  693. }
  694. this.onErrorObservable.notifyObservers(this);
  695. }
  696. if (fallbacks && fallbacks.isMoreFallbacks) {
  697. BABYLON.Tools.Error("Trying next fallback.");
  698. this.defines = fallbacks.reduce(this.defines, this);
  699. this._prepareEffect();
  700. }
  701. else {
  702. if (this.onError) {
  703. this.onError(this, this._compilationError);
  704. }
  705. this.onErrorObservable.notifyObservers(this);
  706. this.onErrorObservable.clear();
  707. // Unbind mesh reference in fallbacks
  708. if (this._fallbacks) {
  709. this._fallbacks.unBindMesh();
  710. }
  711. }
  712. }
  713. };
  714. Object.defineProperty(Effect.prototype, "isSupported", {
  715. /**
  716. * Checks if the effect is supported. (Must be called after compilation)
  717. */
  718. get: function () {
  719. return this._compilationError === "";
  720. },
  721. enumerable: true,
  722. configurable: true
  723. });
  724. /**
  725. * Binds a texture to the engine to be used as output of the shader.
  726. * @param channel Name of the output variable.
  727. * @param texture Texture to bind.
  728. */
  729. Effect.prototype._bindTexture = function (channel, texture) {
  730. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  731. };
  732. /**
  733. * Sets a texture on the engine to be used in the shader.
  734. * @param channel Name of the sampler variable.
  735. * @param texture Texture to set.
  736. */
  737. Effect.prototype.setTexture = function (channel, texture) {
  738. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  739. };
  740. /**
  741. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  742. * @param channel Name of the sampler variable.
  743. * @param texture Texture to set.
  744. */
  745. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  746. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  747. };
  748. /**
  749. * Sets an array of textures on the engine to be used in the shader.
  750. * @param channel Name of the variable.
  751. * @param textures Textures to set.
  752. */
  753. Effect.prototype.setTextureArray = function (channel, textures) {
  754. if (this._samplers.indexOf(channel + "Ex") === -1) {
  755. var initialPos = this._samplers.indexOf(channel);
  756. for (var index = 1; index < textures.length; index++) {
  757. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  758. }
  759. }
  760. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  761. };
  762. /**
  763. * 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)
  764. * @param channel Name of the sampler variable.
  765. * @param postProcess Post process to get the input texture from.
  766. */
  767. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  768. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  769. };
  770. /**
  771. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  772. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  773. * @param channel Name of the sampler variable.
  774. * @param postProcess Post process to get the output texture from.
  775. */
  776. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  777. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  778. };
  779. /** @ignore */
  780. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  781. var cache = this._valueCache[uniformName];
  782. var flag = matrix.updateFlag;
  783. if (cache !== undefined && cache === flag) {
  784. return false;
  785. }
  786. this._valueCache[uniformName] = flag;
  787. return true;
  788. };
  789. /** @ignore */
  790. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  791. var cache = this._valueCache[uniformName];
  792. if (!cache) {
  793. cache = [x, y];
  794. this._valueCache[uniformName] = cache;
  795. return true;
  796. }
  797. var changed = false;
  798. if (cache[0] !== x) {
  799. cache[0] = x;
  800. changed = true;
  801. }
  802. if (cache[1] !== y) {
  803. cache[1] = y;
  804. changed = true;
  805. }
  806. return changed;
  807. };
  808. /** @ignore */
  809. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  810. var cache = this._valueCache[uniformName];
  811. if (!cache) {
  812. cache = [x, y, z];
  813. this._valueCache[uniformName] = cache;
  814. return true;
  815. }
  816. var changed = false;
  817. if (cache[0] !== x) {
  818. cache[0] = x;
  819. changed = true;
  820. }
  821. if (cache[1] !== y) {
  822. cache[1] = y;
  823. changed = true;
  824. }
  825. if (cache[2] !== z) {
  826. cache[2] = z;
  827. changed = true;
  828. }
  829. return changed;
  830. };
  831. /** @ignore */
  832. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  833. var cache = this._valueCache[uniformName];
  834. if (!cache) {
  835. cache = [x, y, z, w];
  836. this._valueCache[uniformName] = cache;
  837. return true;
  838. }
  839. var changed = false;
  840. if (cache[0] !== x) {
  841. cache[0] = x;
  842. changed = true;
  843. }
  844. if (cache[1] !== y) {
  845. cache[1] = y;
  846. changed = true;
  847. }
  848. if (cache[2] !== z) {
  849. cache[2] = z;
  850. changed = true;
  851. }
  852. if (cache[3] !== w) {
  853. cache[3] = w;
  854. changed = true;
  855. }
  856. return changed;
  857. };
  858. /**
  859. * Binds a buffer to a uniform.
  860. * @param buffer Buffer to bind.
  861. * @param name Name of the uniform variable to bind to.
  862. */
  863. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  864. var bufferName = this._uniformBuffersNames[name];
  865. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  866. return;
  867. }
  868. Effect._baseCache[bufferName] = buffer;
  869. this._engine.bindUniformBufferBase(buffer, bufferName);
  870. };
  871. /**
  872. * Binds block to a uniform.
  873. * @param blockName Name of the block to bind.
  874. * @param index Index to bind.
  875. */
  876. Effect.prototype.bindUniformBlock = function (blockName, index) {
  877. this._engine.bindUniformBlock(this._program, blockName, index);
  878. };
  879. /**
  880. * Sets an interger value on a uniform variable.
  881. * @param uniformName Name of the variable.
  882. * @param value Value to be set.
  883. * @returns this effect.
  884. */
  885. Effect.prototype.setInt = function (uniformName, value) {
  886. var cache = this._valueCache[uniformName];
  887. if (cache !== undefined && cache === value)
  888. return this;
  889. this._valueCache[uniformName] = value;
  890. this._engine.setInt(this.getUniform(uniformName), value);
  891. return this;
  892. };
  893. /**
  894. * Sets an int array on a uniform variable.
  895. * @param uniformName Name of the variable.
  896. * @param array array to be set.
  897. * @returns this effect.
  898. */
  899. Effect.prototype.setIntArray = function (uniformName, array) {
  900. this._valueCache[uniformName] = null;
  901. this._engine.setIntArray(this.getUniform(uniformName), array);
  902. return this;
  903. };
  904. /**
  905. * 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)
  906. * @param uniformName Name of the variable.
  907. * @param array array to be set.
  908. * @returns this effect.
  909. */
  910. Effect.prototype.setIntArray2 = function (uniformName, array) {
  911. this._valueCache[uniformName] = null;
  912. this._engine.setIntArray2(this.getUniform(uniformName), array);
  913. return this;
  914. };
  915. /**
  916. * 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)
  917. * @param uniformName Name of the variable.
  918. * @param array array to be set.
  919. * @returns this effect.
  920. */
  921. Effect.prototype.setIntArray3 = function (uniformName, array) {
  922. this._valueCache[uniformName] = null;
  923. this._engine.setIntArray3(this.getUniform(uniformName), array);
  924. return this;
  925. };
  926. /**
  927. * 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)
  928. * @param uniformName Name of the variable.
  929. * @param array array to be set.
  930. * @returns this effect.
  931. */
  932. Effect.prototype.setIntArray4 = function (uniformName, array) {
  933. this._valueCache[uniformName] = null;
  934. this._engine.setIntArray4(this.getUniform(uniformName), array);
  935. return this;
  936. };
  937. /**
  938. * Sets an float array on a uniform variable.
  939. * @param uniformName Name of the variable.
  940. * @param array array to be set.
  941. * @returns this effect.
  942. */
  943. Effect.prototype.setFloatArray = function (uniformName, array) {
  944. this._valueCache[uniformName] = null;
  945. this._engine.setFloatArray(this.getUniform(uniformName), array);
  946. return this;
  947. };
  948. /**
  949. * 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)
  950. * @param uniformName Name of the variable.
  951. * @param array array to be set.
  952. * @returns this effect.
  953. */
  954. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  955. this._valueCache[uniformName] = null;
  956. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  957. return this;
  958. };
  959. /**
  960. * 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)
  961. * @param uniformName Name of the variable.
  962. * @param array array to be set.
  963. * @returns this effect.
  964. */
  965. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  966. this._valueCache[uniformName] = null;
  967. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  968. return this;
  969. };
  970. /**
  971. * 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)
  972. * @param uniformName Name of the variable.
  973. * @param array array to be set.
  974. * @returns this effect.
  975. */
  976. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  977. this._valueCache[uniformName] = null;
  978. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  979. return this;
  980. };
  981. /**
  982. * Sets an array on a uniform variable.
  983. * @param uniformName Name of the variable.
  984. * @param array array to be set.
  985. * @returns this effect.
  986. */
  987. Effect.prototype.setArray = function (uniformName, array) {
  988. this._valueCache[uniformName] = null;
  989. this._engine.setArray(this.getUniform(uniformName), array);
  990. return this;
  991. };
  992. /**
  993. * 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)
  994. * @param uniformName Name of the variable.
  995. * @param array array to be set.
  996. * @returns this effect.
  997. */
  998. Effect.prototype.setArray2 = function (uniformName, array) {
  999. this._valueCache[uniformName] = null;
  1000. this._engine.setArray2(this.getUniform(uniformName), array);
  1001. return this;
  1002. };
  1003. /**
  1004. * 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)
  1005. * @param uniformName Name of the variable.
  1006. * @param array array to be set.
  1007. * @returns this effect.
  1008. */
  1009. Effect.prototype.setArray3 = function (uniformName, array) {
  1010. this._valueCache[uniformName] = null;
  1011. this._engine.setArray3(this.getUniform(uniformName), array);
  1012. return this;
  1013. };
  1014. /**
  1015. * 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)
  1016. * @param uniformName Name of the variable.
  1017. * @param array array to be set.
  1018. * @returns this effect.
  1019. */
  1020. Effect.prototype.setArray4 = function (uniformName, array) {
  1021. this._valueCache[uniformName] = null;
  1022. this._engine.setArray4(this.getUniform(uniformName), array);
  1023. return this;
  1024. };
  1025. /**
  1026. * Sets matrices on a uniform variable.
  1027. * @param uniformName Name of the variable.
  1028. * @param matrices matrices to be set.
  1029. * @returns this effect.
  1030. */
  1031. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1032. if (!matrices) {
  1033. return this;
  1034. }
  1035. this._valueCache[uniformName] = null;
  1036. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1037. return this;
  1038. };
  1039. /**
  1040. * Sets matrix on a uniform variable.
  1041. * @param uniformName Name of the variable.
  1042. * @param matrix matrix to be set.
  1043. * @returns this effect.
  1044. */
  1045. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1046. if (this._cacheMatrix(uniformName, matrix)) {
  1047. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1048. }
  1049. return this;
  1050. };
  1051. /**
  1052. * 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)
  1053. * @param uniformName Name of the variable.
  1054. * @param matrix matrix to be set.
  1055. * @returns this effect.
  1056. */
  1057. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1058. this._valueCache[uniformName] = null;
  1059. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1060. return this;
  1061. };
  1062. /**
  1063. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1064. * @param uniformName Name of the variable.
  1065. * @param matrix matrix to be set.
  1066. * @returns this effect.
  1067. */
  1068. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1069. this._valueCache[uniformName] = null;
  1070. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1071. return this;
  1072. };
  1073. /**
  1074. * Sets a float on a uniform variable.
  1075. * @param uniformName Name of the variable.
  1076. * @param value value to be set.
  1077. * @returns this effect.
  1078. */
  1079. Effect.prototype.setFloat = function (uniformName, value) {
  1080. var cache = this._valueCache[uniformName];
  1081. if (cache !== undefined && cache === value)
  1082. return this;
  1083. this._valueCache[uniformName] = value;
  1084. this._engine.setFloat(this.getUniform(uniformName), value);
  1085. return this;
  1086. };
  1087. /**
  1088. * Sets a boolean on a uniform variable.
  1089. * @param uniformName Name of the variable.
  1090. * @param bool value to be set.
  1091. * @returns this effect.
  1092. */
  1093. Effect.prototype.setBool = function (uniformName, bool) {
  1094. var cache = this._valueCache[uniformName];
  1095. if (cache !== undefined && cache === bool)
  1096. return this;
  1097. this._valueCache[uniformName] = bool;
  1098. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1099. return this;
  1100. };
  1101. /**
  1102. * Sets a Vector2 on a uniform variable.
  1103. * @param uniformName Name of the variable.
  1104. * @param vector2 vector2 to be set.
  1105. * @returns this effect.
  1106. */
  1107. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1108. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1109. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1110. }
  1111. return this;
  1112. };
  1113. /**
  1114. * Sets a float2 on a uniform variable.
  1115. * @param uniformName Name of the variable.
  1116. * @param x First float in float2.
  1117. * @param y Second float in float2.
  1118. * @returns this effect.
  1119. */
  1120. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1121. if (this._cacheFloat2(uniformName, x, y)) {
  1122. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1123. }
  1124. return this;
  1125. };
  1126. /**
  1127. * Sets a Vector3 on a uniform variable.
  1128. * @param uniformName Name of the variable.
  1129. * @param vector3 Value to be set.
  1130. * @returns this effect.
  1131. */
  1132. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1133. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1134. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1135. }
  1136. return this;
  1137. };
  1138. /**
  1139. * Sets a float3 on a uniform variable.
  1140. * @param uniformName Name of the variable.
  1141. * @param x First float in float3.
  1142. * @param y Second float in float3.
  1143. * @param z Third float in float3.
  1144. * @returns this effect.
  1145. */
  1146. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1147. if (this._cacheFloat3(uniformName, x, y, z)) {
  1148. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1149. }
  1150. return this;
  1151. };
  1152. /**
  1153. * Sets a Vector4 on a uniform variable.
  1154. * @param uniformName Name of the variable.
  1155. * @param vector4 Value to be set.
  1156. * @returns this effect.
  1157. */
  1158. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1159. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1160. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1161. }
  1162. return this;
  1163. };
  1164. /**
  1165. * Sets a float4 on a uniform variable.
  1166. * @param uniformName Name of the variable.
  1167. * @param x First float in float4.
  1168. * @param y Second float in float4.
  1169. * @param z Third float in float4.
  1170. * @param w Fourth float in float4.
  1171. * @returns this effect.
  1172. */
  1173. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1174. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1175. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1176. }
  1177. return this;
  1178. };
  1179. /**
  1180. * Sets a Color3 on a uniform variable.
  1181. * @param uniformName Name of the variable.
  1182. * @param color3 Value to be set.
  1183. * @returns this effect.
  1184. */
  1185. Effect.prototype.setColor3 = function (uniformName, color3) {
  1186. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1187. this._engine.setColor3(this.getUniform(uniformName), color3);
  1188. }
  1189. return this;
  1190. };
  1191. /**
  1192. * Sets a Color4 on a uniform variable.
  1193. * @param uniformName Name of the variable.
  1194. * @param color3 Value to be set.
  1195. * @param alpha Alpha value to be set.
  1196. * @returns this effect.
  1197. */
  1198. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1199. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1200. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1201. }
  1202. return this;
  1203. };
  1204. /**
  1205. * Sets a Color4 on a uniform variable
  1206. * @param uniformName defines the name of the variable
  1207. * @param color4 defines the value to be set
  1208. * @returns this effect.
  1209. */
  1210. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1211. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1212. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1213. }
  1214. return this;
  1215. };
  1216. /**
  1217. * Resets the cache of effects.
  1218. */
  1219. Effect.ResetCache = function () {
  1220. Effect._baseCache = {};
  1221. };
  1222. Effect._uniqueIdSeed = 0;
  1223. Effect._baseCache = {};
  1224. /**
  1225. * Store of each shader (The can be looked up using effect.key)
  1226. */
  1227. Effect.ShadersStore = {};
  1228. /**
  1229. * Store of each included file for a shader (The can be looked up using effect.key)
  1230. */
  1231. Effect.IncludesShadersStore = {};
  1232. return Effect;
  1233. }());
  1234. BABYLON.Effect = Effect;
  1235. })(BABYLON || (BABYLON = {}));
  1236. //# sourceMappingURL=babylon.effect.js.map
  1237. "use strict";
  1238. //# sourceMappingURL=babylon.types.js.map
  1239. "use strict";
  1240. var BABYLON;
  1241. (function (BABYLON) {
  1242. var KeyboardEventTypes = /** @class */ (function () {
  1243. function KeyboardEventTypes() {
  1244. }
  1245. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1246. get: function () {
  1247. return KeyboardEventTypes._KEYDOWN;
  1248. },
  1249. enumerable: true,
  1250. configurable: true
  1251. });
  1252. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1253. get: function () {
  1254. return KeyboardEventTypes._KEYUP;
  1255. },
  1256. enumerable: true,
  1257. configurable: true
  1258. });
  1259. KeyboardEventTypes._KEYDOWN = 0x01;
  1260. KeyboardEventTypes._KEYUP = 0x02;
  1261. return KeyboardEventTypes;
  1262. }());
  1263. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1264. var KeyboardInfo = /** @class */ (function () {
  1265. function KeyboardInfo(type, event) {
  1266. this.type = type;
  1267. this.event = event;
  1268. }
  1269. return KeyboardInfo;
  1270. }());
  1271. BABYLON.KeyboardInfo = KeyboardInfo;
  1272. /**
  1273. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1274. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1275. */
  1276. var KeyboardInfoPre = /** @class */ (function (_super) {
  1277. __extends(KeyboardInfoPre, _super);
  1278. function KeyboardInfoPre(type, event) {
  1279. var _this = _super.call(this, type, event) || this;
  1280. _this.skipOnPointerObservable = false;
  1281. return _this;
  1282. }
  1283. return KeyboardInfoPre;
  1284. }(KeyboardInfo));
  1285. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1286. })(BABYLON || (BABYLON = {}));
  1287. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1288. "use strict";
  1289. var BABYLON;
  1290. (function (BABYLON) {
  1291. var PointerEventTypes = /** @class */ (function () {
  1292. function PointerEventTypes() {
  1293. }
  1294. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1295. get: function () {
  1296. return PointerEventTypes._POINTERDOWN;
  1297. },
  1298. enumerable: true,
  1299. configurable: true
  1300. });
  1301. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1302. get: function () {
  1303. return PointerEventTypes._POINTERUP;
  1304. },
  1305. enumerable: true,
  1306. configurable: true
  1307. });
  1308. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1309. get: function () {
  1310. return PointerEventTypes._POINTERMOVE;
  1311. },
  1312. enumerable: true,
  1313. configurable: true
  1314. });
  1315. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1316. get: function () {
  1317. return PointerEventTypes._POINTERWHEEL;
  1318. },
  1319. enumerable: true,
  1320. configurable: true
  1321. });
  1322. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1323. get: function () {
  1324. return PointerEventTypes._POINTERPICK;
  1325. },
  1326. enumerable: true,
  1327. configurable: true
  1328. });
  1329. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1330. get: function () {
  1331. return PointerEventTypes._POINTERTAP;
  1332. },
  1333. enumerable: true,
  1334. configurable: true
  1335. });
  1336. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1337. get: function () {
  1338. return PointerEventTypes._POINTERDOUBLETAP;
  1339. },
  1340. enumerable: true,
  1341. configurable: true
  1342. });
  1343. PointerEventTypes._POINTERDOWN = 0x01;
  1344. PointerEventTypes._POINTERUP = 0x02;
  1345. PointerEventTypes._POINTERMOVE = 0x04;
  1346. PointerEventTypes._POINTERWHEEL = 0x08;
  1347. PointerEventTypes._POINTERPICK = 0x10;
  1348. PointerEventTypes._POINTERTAP = 0x20;
  1349. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1350. return PointerEventTypes;
  1351. }());
  1352. BABYLON.PointerEventTypes = PointerEventTypes;
  1353. var PointerInfoBase = /** @class */ (function () {
  1354. function PointerInfoBase(type, event) {
  1355. this.type = type;
  1356. this.event = event;
  1357. }
  1358. return PointerInfoBase;
  1359. }());
  1360. BABYLON.PointerInfoBase = PointerInfoBase;
  1361. /**
  1362. * This class is used to store pointer related info for the onPrePointerObservable event.
  1363. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1364. */
  1365. var PointerInfoPre = /** @class */ (function (_super) {
  1366. __extends(PointerInfoPre, _super);
  1367. function PointerInfoPre(type, event, localX, localY) {
  1368. var _this = _super.call(this, type, event) || this;
  1369. _this.skipOnPointerObservable = false;
  1370. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1371. return _this;
  1372. }
  1373. return PointerInfoPre;
  1374. }(PointerInfoBase));
  1375. BABYLON.PointerInfoPre = PointerInfoPre;
  1376. /**
  1377. * This type contains all the data related to a pointer event in Babylon.js.
  1378. * 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.
  1379. */
  1380. var PointerInfo = /** @class */ (function (_super) {
  1381. __extends(PointerInfo, _super);
  1382. function PointerInfo(type, event, pickInfo) {
  1383. var _this = _super.call(this, type, event) || this;
  1384. _this.pickInfo = pickInfo;
  1385. return _this;
  1386. }
  1387. return PointerInfo;
  1388. }(PointerInfoBase));
  1389. BABYLON.PointerInfo = PointerInfo;
  1390. })(BABYLON || (BABYLON = {}));
  1391. //# sourceMappingURL=babylon.pointerEvents.js.map
  1392. "use strict";
  1393. var BABYLON;
  1394. (function (BABYLON) {
  1395. BABYLON.ToGammaSpace = 1 / 2.2;
  1396. BABYLON.ToLinearSpace = 2.2;
  1397. BABYLON.Epsilon = 0.001;
  1398. /**
  1399. * Class used to hold a RBG color
  1400. */
  1401. var Color3 = /** @class */ (function () {
  1402. /**
  1403. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1404. * @param r defines the red component (between 0 and 1, default is 0)
  1405. * @param g defines the green component (between 0 and 1, default is 0)
  1406. * @param b defines the blue component (between 0 and 1, default is 0)
  1407. */
  1408. function Color3(
  1409. /**
  1410. * Defines the red component (between 0 and 1, default is 0)
  1411. */
  1412. r,
  1413. /**
  1414. * Defines the green component (between 0 and 1, default is 0)
  1415. */
  1416. g,
  1417. /**
  1418. * Defines the blue component (between 0 and 1, default is 0)
  1419. */
  1420. b) {
  1421. if (r === void 0) { r = 0; }
  1422. if (g === void 0) { g = 0; }
  1423. if (b === void 0) { b = 0; }
  1424. this.r = r;
  1425. this.g = g;
  1426. this.b = b;
  1427. }
  1428. /**
  1429. * Creates a string with the Color3 current values
  1430. * @returns the string representation of the Color3 object
  1431. */
  1432. Color3.prototype.toString = function () {
  1433. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1434. };
  1435. /**
  1436. * Returns the string "Color3"
  1437. * @returns "Color3"
  1438. */
  1439. Color3.prototype.getClassName = function () {
  1440. return "Color3";
  1441. };
  1442. /**
  1443. * Compute the Color3 hash code
  1444. * @returns an unique number that can be used to hash Color3 objects
  1445. */
  1446. Color3.prototype.getHashCode = function () {
  1447. var hash = this.r || 0;
  1448. hash = (hash * 397) ^ (this.g || 0);
  1449. hash = (hash * 397) ^ (this.b || 0);
  1450. return hash;
  1451. };
  1452. // Operators
  1453. /**
  1454. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1455. * @param array defines the array where to store the r,g,b components
  1456. * @param index defines an optional index in the target array to define where to start storing values
  1457. * @returns the current Color3 object
  1458. */
  1459. Color3.prototype.toArray = function (array, index) {
  1460. if (index === undefined) {
  1461. index = 0;
  1462. }
  1463. array[index] = this.r;
  1464. array[index + 1] = this.g;
  1465. array[index + 2] = this.b;
  1466. return this;
  1467. };
  1468. /**
  1469. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1470. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1471. * @returns a new {BABYLON.Color4} object
  1472. */
  1473. Color3.prototype.toColor4 = function (alpha) {
  1474. if (alpha === void 0) { alpha = 1; }
  1475. return new Color4(this.r, this.g, this.b, alpha);
  1476. };
  1477. /**
  1478. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1479. * @returns the new array
  1480. */
  1481. Color3.prototype.asArray = function () {
  1482. var result = new Array();
  1483. this.toArray(result, 0);
  1484. return result;
  1485. };
  1486. /**
  1487. * Returns the luminance value
  1488. * @returns a float value
  1489. */
  1490. Color3.prototype.toLuminance = function () {
  1491. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1492. };
  1493. /**
  1494. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1495. * @param otherColor defines the second operand
  1496. * @returns the new Color3 object
  1497. */
  1498. Color3.prototype.multiply = function (otherColor) {
  1499. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1500. };
  1501. /**
  1502. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1503. * @param otherColor defines the second operand
  1504. * @param result defines the Color3 object where to store the result
  1505. * @returns the current Color3
  1506. */
  1507. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1508. result.r = this.r * otherColor.r;
  1509. result.g = this.g * otherColor.g;
  1510. result.b = this.b * otherColor.b;
  1511. return this;
  1512. };
  1513. /**
  1514. * Determines equality between Color3 objects
  1515. * @param otherColor defines the second operand
  1516. * @returns true if the rgb values are equal to the passed ones
  1517. */
  1518. Color3.prototype.equals = function (otherColor) {
  1519. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1520. };
  1521. /**
  1522. * Determines equality between the current Color3 object and a set of r,b,g values
  1523. * @param r defines the red component to check
  1524. * @param g defines the green component to check
  1525. * @param b defines the blue component to check
  1526. * @returns true if the rgb values are equal to the passed ones
  1527. */
  1528. Color3.prototype.equalsFloats = function (r, g, b) {
  1529. return this.r === r && this.g === g && this.b === b;
  1530. };
  1531. /**
  1532. * Multiplies in place each rgb value by scale
  1533. * @param scale defines the scaling factor
  1534. * @returns the updated Color3
  1535. */
  1536. Color3.prototype.scale = function (scale) {
  1537. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1538. };
  1539. /**
  1540. * Multiplies the rgb values by scale and stores the result into "result"
  1541. * @param scale defines the scaling factor
  1542. * @param result defines the Color3 object where to store the result
  1543. * @returns the unmodified current Color3
  1544. */
  1545. Color3.prototype.scaleToRef = function (scale, result) {
  1546. result.r = this.r * scale;
  1547. result.g = this.g * scale;
  1548. result.b = this.b * scale;
  1549. return this;
  1550. };
  1551. /**
  1552. * Scale the current Color3 values by a factor and add the result to a given Color3
  1553. * @param scale defines the scale factor
  1554. * @param result defines color to store the result into
  1555. * @returns the unmodified current Color3
  1556. */
  1557. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1558. result.r += this.r * scale;
  1559. result.g += this.g * scale;
  1560. result.b += this.b * scale;
  1561. return this;
  1562. };
  1563. /**
  1564. * Clamps the rgb values by the min and max values and stores the result into "result"
  1565. * @param min defines minimum clamping value (default is 0)
  1566. * @param max defines maximum clamping value (default is 1)
  1567. * @param result defines color to store the result into
  1568. * @returns the original Color3
  1569. */
  1570. Color3.prototype.clampToRef = function (min, max, result) {
  1571. if (min === void 0) { min = 0; }
  1572. if (max === void 0) { max = 1; }
  1573. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1574. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1575. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1576. return this;
  1577. };
  1578. /**
  1579. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1580. * @param otherColor defines the second operand
  1581. * @returns the new Color3
  1582. */
  1583. Color3.prototype.add = function (otherColor) {
  1584. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1585. };
  1586. /**
  1587. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1588. * @param otherColor defines the second operand
  1589. * @param result defines Color3 object to store the result into
  1590. * @returns the unmodified current Color3
  1591. */
  1592. Color3.prototype.addToRef = function (otherColor, result) {
  1593. result.r = this.r + otherColor.r;
  1594. result.g = this.g + otherColor.g;
  1595. result.b = this.b + otherColor.b;
  1596. return this;
  1597. };
  1598. /**
  1599. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1600. * @param otherColor defines the second operand
  1601. * @returns the new Color3
  1602. */
  1603. Color3.prototype.subtract = function (otherColor) {
  1604. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1605. };
  1606. /**
  1607. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1608. * @param otherColor defines the second operand
  1609. * @param result defines Color3 object to store the result into
  1610. * @returns the unmodified current Color3
  1611. */
  1612. Color3.prototype.subtractToRef = function (otherColor, result) {
  1613. result.r = this.r - otherColor.r;
  1614. result.g = this.g - otherColor.g;
  1615. result.b = this.b - otherColor.b;
  1616. return this;
  1617. };
  1618. /**
  1619. * Copy the current object
  1620. * @returns a new Color3 copied the current one
  1621. */
  1622. Color3.prototype.clone = function () {
  1623. return new Color3(this.r, this.g, this.b);
  1624. };
  1625. /**
  1626. * Copies the rgb values from the source in the current Color3
  1627. * @param source defines the source Color3 object
  1628. * @returns the updated Color3 object
  1629. */
  1630. Color3.prototype.copyFrom = function (source) {
  1631. this.r = source.r;
  1632. this.g = source.g;
  1633. this.b = source.b;
  1634. return this;
  1635. };
  1636. /**
  1637. * Updates the Color3 rgb values from the passed floats
  1638. * @param r defines the red component to read from
  1639. * @param g defines the green component to read from
  1640. * @param b defines the blue component to read from
  1641. * @returns the current Color3 object
  1642. */
  1643. Color3.prototype.copyFromFloats = function (r, g, b) {
  1644. this.r = r;
  1645. this.g = g;
  1646. this.b = b;
  1647. return this;
  1648. };
  1649. /**
  1650. * Updates the Color3 rgb values from the passed floats
  1651. * @param r defines the red component to read from
  1652. * @param g defines the green component to read from
  1653. * @param b defines the blue component to read from
  1654. * @returns the current Color3 object
  1655. */
  1656. Color3.prototype.set = function (r, g, b) {
  1657. return this.copyFromFloats(r, g, b);
  1658. };
  1659. /**
  1660. * Compute the Color3 hexadecimal code as a string
  1661. * @returns a string containing the hexadecimal representation of the Color3 object
  1662. */
  1663. Color3.prototype.toHexString = function () {
  1664. var intR = (this.r * 255) | 0;
  1665. var intG = (this.g * 255) | 0;
  1666. var intB = (this.b * 255) | 0;
  1667. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1668. };
  1669. /**
  1670. * Computes a new Color3 converted from the current one to linear space
  1671. * @returns a new Color3 object
  1672. */
  1673. Color3.prototype.toLinearSpace = function () {
  1674. var convertedColor = new Color3();
  1675. this.toLinearSpaceToRef(convertedColor);
  1676. return convertedColor;
  1677. };
  1678. /**
  1679. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1680. * @param convertedColor defines the Color3 object where to store the linear space version
  1681. * @returns the unmodified Color3
  1682. */
  1683. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1684. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1685. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1686. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1687. return this;
  1688. };
  1689. /**
  1690. * Computes a new Color3 converted from the current one to gamma space
  1691. * @returns a new Color3 object
  1692. */
  1693. Color3.prototype.toGammaSpace = function () {
  1694. var convertedColor = new Color3();
  1695. this.toGammaSpaceToRef(convertedColor);
  1696. return convertedColor;
  1697. };
  1698. /**
  1699. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1700. * @param convertedColor defines the Color3 object where to store the gamma space version
  1701. * @returns the unmodified Color3
  1702. */
  1703. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1704. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1705. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1706. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1707. return this;
  1708. };
  1709. // Statics
  1710. /**
  1711. * Creates a new Color3 from the string containing valid hexadecimal values
  1712. * @param hex defines a string containing valid hexadecimal values
  1713. * @returns a new Color3 object
  1714. */
  1715. Color3.FromHexString = function (hex) {
  1716. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1717. return new Color3(0, 0, 0);
  1718. }
  1719. var r = parseInt(hex.substring(1, 3), 16);
  1720. var g = parseInt(hex.substring(3, 5), 16);
  1721. var b = parseInt(hex.substring(5, 7), 16);
  1722. return Color3.FromInts(r, g, b);
  1723. };
  1724. /**
  1725. * Creates a new Vector3 from the starting index of the passed array
  1726. * @param array defines the source array
  1727. * @param offset defines an offset in the source array
  1728. * @returns a new Color3 object
  1729. */
  1730. Color3.FromArray = function (array, offset) {
  1731. if (offset === void 0) { offset = 0; }
  1732. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1733. };
  1734. /**
  1735. * Creates a new Color3 from integer values (< 256)
  1736. * @param r defines the red component to read from (value between 0 and 255)
  1737. * @param g defines the green component to read from (value between 0 and 255)
  1738. * @param b defines the blue component to read from (value between 0 and 255)
  1739. * @returns a new Color3 object
  1740. */
  1741. Color3.FromInts = function (r, g, b) {
  1742. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1743. };
  1744. /**
  1745. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1746. * @param start defines the start Color3 value
  1747. * @param end defines the end Color3 value
  1748. * @param amount defines the gradient value between start and end
  1749. * @returns a new Color3 object
  1750. */
  1751. Color3.Lerp = function (start, end, amount) {
  1752. var r = start.r + ((end.r - start.r) * amount);
  1753. var g = start.g + ((end.g - start.g) * amount);
  1754. var b = start.b + ((end.b - start.b) * amount);
  1755. return new Color3(r, g, b);
  1756. };
  1757. /**
  1758. * Returns a Color3 value containing a red color
  1759. * @returns a new Color3 object
  1760. */
  1761. Color3.Red = function () { return new Color3(1, 0, 0); };
  1762. /**
  1763. * Returns a Color3 value containing a green color
  1764. * @returns a new Color3 object
  1765. */
  1766. Color3.Green = function () { return new Color3(0, 1, 0); };
  1767. /**
  1768. * Returns a Color3 value containing a blue color
  1769. * @returns a new Color3 object
  1770. */
  1771. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1772. /**
  1773. * Returns a Color3 value containing a black color
  1774. * @returns a new Color3 object
  1775. */
  1776. Color3.Black = function () { return new Color3(0, 0, 0); };
  1777. /**
  1778. * Returns a Color3 value containing a white color
  1779. * @returns a new Color3 object
  1780. */
  1781. Color3.White = function () { return new Color3(1, 1, 1); };
  1782. /**
  1783. * Returns a Color3 value containing a purple color
  1784. * @returns a new Color3 object
  1785. */
  1786. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1787. /**
  1788. * Returns a Color3 value containing a magenta color
  1789. * @returns a new Color3 object
  1790. */
  1791. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1792. /**
  1793. * Returns a Color3 value containing a yellow color
  1794. * @returns a new Color3 object
  1795. */
  1796. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1797. /**
  1798. * Returns a Color3 value containing a gray color
  1799. * @returns a new Color3 object
  1800. */
  1801. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1802. /**
  1803. * Returns a Color3 value containing a teal color
  1804. * @returns a new Color3 object
  1805. */
  1806. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1807. /**
  1808. * Returns a Color3 value containing a random color
  1809. * @returns a new Color3 object
  1810. */
  1811. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1812. return Color3;
  1813. }());
  1814. BABYLON.Color3 = Color3;
  1815. /**
  1816. * Class used to hold a RBGA color
  1817. */
  1818. var Color4 = /** @class */ (function () {
  1819. /**
  1820. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1821. * @param r defines the red component (between 0 and 1, default is 0)
  1822. * @param g defines the green component (between 0 and 1, default is 0)
  1823. * @param b defines the blue component (between 0 and 1, default is 0)
  1824. * @param a defines the alpha component (between 0 and 1, default is 1)
  1825. */
  1826. function Color4(
  1827. /**
  1828. * Defines the red component (between 0 and 1, default is 0)
  1829. */
  1830. r,
  1831. /**
  1832. * Defines the green component (between 0 and 1, default is 0)
  1833. */
  1834. g,
  1835. /**
  1836. * Defines the blue component (between 0 and 1, default is 0)
  1837. */
  1838. b,
  1839. /**
  1840. * Defines the alpha component (between 0 and 1, default is 1)
  1841. */
  1842. a) {
  1843. if (r === void 0) { r = 0; }
  1844. if (g === void 0) { g = 0; }
  1845. if (b === void 0) { b = 0; }
  1846. if (a === void 0) { a = 1; }
  1847. this.r = r;
  1848. this.g = g;
  1849. this.b = b;
  1850. this.a = a;
  1851. }
  1852. // Operators
  1853. /**
  1854. * Adds in place the passed Color4 values to the current Color4 object
  1855. * @param right defines the second operand
  1856. * @returns the current updated Color4 object
  1857. */
  1858. Color4.prototype.addInPlace = function (right) {
  1859. this.r += right.r;
  1860. this.g += right.g;
  1861. this.b += right.b;
  1862. this.a += right.a;
  1863. return this;
  1864. };
  1865. /**
  1866. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1867. * @returns the new array
  1868. */
  1869. Color4.prototype.asArray = function () {
  1870. var result = new Array();
  1871. this.toArray(result, 0);
  1872. return result;
  1873. };
  1874. /**
  1875. * Stores from the starting index in the passed array the Color4 successive values
  1876. * @param array defines the array where to store the r,g,b components
  1877. * @param index defines an optional index in the target array to define where to start storing values
  1878. * @returns the current Color4 object
  1879. */
  1880. Color4.prototype.toArray = function (array, index) {
  1881. if (index === undefined) {
  1882. index = 0;
  1883. }
  1884. array[index] = this.r;
  1885. array[index + 1] = this.g;
  1886. array[index + 2] = this.b;
  1887. array[index + 3] = this.a;
  1888. return this;
  1889. };
  1890. /**
  1891. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1892. * @param right defines the second operand
  1893. * @returns a new Color4 object
  1894. */
  1895. Color4.prototype.add = function (right) {
  1896. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1897. };
  1898. /**
  1899. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1900. * @param right defines the second operand
  1901. * @returns a new Color4 object
  1902. */
  1903. Color4.prototype.subtract = function (right) {
  1904. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1905. };
  1906. /**
  1907. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1908. * @param right defines the second operand
  1909. * @param result defines the Color4 object where to store the result
  1910. * @returns the current Color4 object
  1911. */
  1912. Color4.prototype.subtractToRef = function (right, result) {
  1913. result.r = this.r - right.r;
  1914. result.g = this.g - right.g;
  1915. result.b = this.b - right.b;
  1916. result.a = this.a - right.a;
  1917. return this;
  1918. };
  1919. /**
  1920. * Creates a new Color4 with the current Color4 values multiplied by scale
  1921. * @param scale defines the scaling factor to apply
  1922. * @returns a new Color4 object
  1923. */
  1924. Color4.prototype.scale = function (scale) {
  1925. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1926. };
  1927. /**
  1928. * Multiplies the current Color4 values by scale and stores the result in "result"
  1929. * @param scale defines the scaling factor to apply
  1930. * @param result defines the Color4 object where to store the result
  1931. * @returns the current unmodified Color4
  1932. */
  1933. Color4.prototype.scaleToRef = function (scale, result) {
  1934. result.r = this.r * scale;
  1935. result.g = this.g * scale;
  1936. result.b = this.b * scale;
  1937. result.a = this.a * scale;
  1938. return this;
  1939. };
  1940. /**
  1941. * Scale the current Color4 values by a factor and add the result to a given Color4
  1942. * @param scale defines the scale factor
  1943. * @param result defines the Color4 object where to store the result
  1944. * @returns the unmodified current Color4
  1945. */
  1946. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1947. result.r += this.r * scale;
  1948. result.g += this.g * scale;
  1949. result.b += this.b * scale;
  1950. result.a += this.a * scale;
  1951. return this;
  1952. };
  1953. /**
  1954. * Clamps the rgb values by the min and max values and stores the result into "result"
  1955. * @param min defines minimum clamping value (default is 0)
  1956. * @param max defines maximum clamping value (default is 1)
  1957. * @param result defines color to store the result into.
  1958. * @returns the cuurent Color4
  1959. */
  1960. Color4.prototype.clampToRef = function (min, max, result) {
  1961. if (min === void 0) { min = 0; }
  1962. if (max === void 0) { max = 1; }
  1963. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1964. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1965. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1966. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1967. return this;
  1968. };
  1969. /**
  1970. * Multipy an Color4 value by another and return a new Color4 object
  1971. * @param color defines the Color4 value to multiply by
  1972. * @returns a new Color4 object
  1973. */
  1974. Color4.prototype.multiply = function (color) {
  1975. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1976. };
  1977. /**
  1978. * Multipy a Color4 value by another and push the result in a reference value
  1979. * @param color defines the Color4 value to multiply by
  1980. * @param result defines the Color4 to fill the result in
  1981. * @returns the result Color4
  1982. */
  1983. Color4.prototype.multiplyToRef = function (color, result) {
  1984. result.r = this.r * color.r;
  1985. result.g = this.g * color.g;
  1986. result.b = this.b * color.b;
  1987. result.a = this.a * color.a;
  1988. return result;
  1989. };
  1990. /**
  1991. * Creates a string with the Color4 current values
  1992. * @returns the string representation of the Color4 object
  1993. */
  1994. Color4.prototype.toString = function () {
  1995. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1996. };
  1997. /**
  1998. * Returns the string "Color4"
  1999. * @returns "Color4"
  2000. */
  2001. Color4.prototype.getClassName = function () {
  2002. return "Color4";
  2003. };
  2004. /**
  2005. * Compute the Color4 hash code
  2006. * @returns an unique number that can be used to hash Color4 objects
  2007. */
  2008. Color4.prototype.getHashCode = function () {
  2009. var hash = this.r || 0;
  2010. hash = (hash * 397) ^ (this.g || 0);
  2011. hash = (hash * 397) ^ (this.b || 0);
  2012. hash = (hash * 397) ^ (this.a || 0);
  2013. return hash;
  2014. };
  2015. /**
  2016. * Creates a new Color4 copied from the current one
  2017. * @returns a new Color4 object
  2018. */
  2019. Color4.prototype.clone = function () {
  2020. return new Color4(this.r, this.g, this.b, this.a);
  2021. };
  2022. /**
  2023. * Copies the passed Color4 values into the current one
  2024. * @param source defines the source Color4 object
  2025. * @returns the current updated Color4 object
  2026. */
  2027. Color4.prototype.copyFrom = function (source) {
  2028. this.r = source.r;
  2029. this.g = source.g;
  2030. this.b = source.b;
  2031. this.a = source.a;
  2032. return this;
  2033. };
  2034. /**
  2035. * Copies the passed float values into the current one
  2036. * @param r defines the red component to read from
  2037. * @param g defines the green component to read from
  2038. * @param b defines the blue component to read from
  2039. * @param a defines the alpha component to read from
  2040. * @returns the current updated Color4 object
  2041. */
  2042. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2043. this.r = r;
  2044. this.g = g;
  2045. this.b = b;
  2046. this.a = a;
  2047. return this;
  2048. };
  2049. /**
  2050. * Copies the passed float values into the current one
  2051. * @param r defines the red component to read from
  2052. * @param g defines the green component to read from
  2053. * @param b defines the blue component to read from
  2054. * @param a defines the alpha component to read from
  2055. * @returns the current updated Color4 object
  2056. */
  2057. Color4.prototype.set = function (r, g, b, a) {
  2058. return this.copyFromFloats(r, g, b, a);
  2059. };
  2060. /**
  2061. * Compute the Color4 hexadecimal code as a string
  2062. * @returns a string containing the hexadecimal representation of the Color4 object
  2063. */
  2064. Color4.prototype.toHexString = function () {
  2065. var intR = (this.r * 255) | 0;
  2066. var intG = (this.g * 255) | 0;
  2067. var intB = (this.b * 255) | 0;
  2068. var intA = (this.a * 255) | 0;
  2069. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2070. };
  2071. /**
  2072. * Computes a new Color4 converted from the current one to linear space
  2073. * @returns a new Color4 object
  2074. */
  2075. Color4.prototype.toLinearSpace = function () {
  2076. var convertedColor = new Color4();
  2077. this.toLinearSpaceToRef(convertedColor);
  2078. return convertedColor;
  2079. };
  2080. /**
  2081. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2082. * @param convertedColor defines the Color4 object where to store the linear space version
  2083. * @returns the unmodified Color4
  2084. */
  2085. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2086. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2087. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2088. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2089. convertedColor.a = this.a;
  2090. return this;
  2091. };
  2092. /**
  2093. * Computes a new Color4 converted from the current one to gamma space
  2094. * @returns a new Color4 object
  2095. */
  2096. Color4.prototype.toGammaSpace = function () {
  2097. var convertedColor = new Color4();
  2098. this.toGammaSpaceToRef(convertedColor);
  2099. return convertedColor;
  2100. };
  2101. /**
  2102. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2103. * @param convertedColor defines the Color4 object where to store the gamma space version
  2104. * @returns the unmodified Color4
  2105. */
  2106. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2107. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2108. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2109. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2110. convertedColor.a = this.a;
  2111. return this;
  2112. };
  2113. // Statics
  2114. /**
  2115. * Creates a new Color4 from the string containing valid hexadecimal values
  2116. * @param hex defines a string containing valid hexadecimal values
  2117. * @returns a new Color4 object
  2118. */
  2119. Color4.FromHexString = function (hex) {
  2120. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2121. return new Color4(0.0, 0.0, 0.0, 0.0);
  2122. }
  2123. var r = parseInt(hex.substring(1, 3), 16);
  2124. var g = parseInt(hex.substring(3, 5), 16);
  2125. var b = parseInt(hex.substring(5, 7), 16);
  2126. var a = parseInt(hex.substring(7, 9), 16);
  2127. return Color4.FromInts(r, g, b, a);
  2128. };
  2129. /**
  2130. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2131. * @param left defines the start value
  2132. * @param right defines the end value
  2133. * @param amount defines the gradient factor
  2134. * @returns a new Color4 object
  2135. */
  2136. Color4.Lerp = function (left, right, amount) {
  2137. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2138. Color4.LerpToRef(left, right, amount, result);
  2139. return result;
  2140. };
  2141. /**
  2142. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2143. * @param left defines the start value
  2144. * @param right defines the end value
  2145. * @param amount defines the gradient factor
  2146. * @param result defines the Color4 object where to store data
  2147. */
  2148. Color4.LerpToRef = function (left, right, amount, result) {
  2149. result.r = left.r + (right.r - left.r) * amount;
  2150. result.g = left.g + (right.g - left.g) * amount;
  2151. result.b = left.b + (right.b - left.b) * amount;
  2152. result.a = left.a + (right.a - left.a) * amount;
  2153. };
  2154. /**
  2155. * Creates a new Color4 from the starting index element of the passed array
  2156. * @param array defines the source array to read from
  2157. * @param offset defines the offset in the source array
  2158. * @returns a new Color4 object
  2159. */
  2160. Color4.FromArray = function (array, offset) {
  2161. if (offset === void 0) { offset = 0; }
  2162. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2163. };
  2164. /**
  2165. * Creates a new Color3 from integer values (< 256)
  2166. * @param r defines the red component to read from (value between 0 and 255)
  2167. * @param g defines the green component to read from (value between 0 and 255)
  2168. * @param b defines the blue component to read from (value between 0 and 255)
  2169. * @param a defines the alpha component to read from (value between 0 and 255)
  2170. * @returns a new Color3 object
  2171. */
  2172. Color4.FromInts = function (r, g, b, a) {
  2173. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2174. };
  2175. /**
  2176. * Check the content of a given array and convert it to an array containing RGBA data
  2177. * If the original array was already containing count * 4 values then it is returned directly
  2178. * @param colors defines the array to check
  2179. * @param count defines the number of RGBA data to expect
  2180. * @returns an array containing count * 4 values (RGBA)
  2181. */
  2182. Color4.CheckColors4 = function (colors, count) {
  2183. // Check if color3 was used
  2184. if (colors.length === count * 3) {
  2185. var colors4 = [];
  2186. for (var index = 0; index < colors.length; index += 3) {
  2187. var newIndex = (index / 3) * 4;
  2188. colors4[newIndex] = colors[index];
  2189. colors4[newIndex + 1] = colors[index + 1];
  2190. colors4[newIndex + 2] = colors[index + 2];
  2191. colors4[newIndex + 3] = 1.0;
  2192. }
  2193. return colors4;
  2194. }
  2195. return colors;
  2196. };
  2197. return Color4;
  2198. }());
  2199. BABYLON.Color4 = Color4;
  2200. var Vector2 = /** @class */ (function () {
  2201. /**
  2202. * Creates a new Vector2 from the passed x and y coordinates.
  2203. */
  2204. function Vector2(x, y) {
  2205. this.x = x;
  2206. this.y = y;
  2207. }
  2208. /**
  2209. * Returns a string with the Vector2 coordinates.
  2210. */
  2211. Vector2.prototype.toString = function () {
  2212. return "{X: " + this.x + " Y:" + this.y + "}";
  2213. };
  2214. /**
  2215. * Returns the string "Vector2"
  2216. */
  2217. Vector2.prototype.getClassName = function () {
  2218. return "Vector2";
  2219. };
  2220. /**
  2221. * Returns the Vector2 hash code as a number.
  2222. */
  2223. Vector2.prototype.getHashCode = function () {
  2224. var hash = this.x || 0;
  2225. hash = (hash * 397) ^ (this.y || 0);
  2226. return hash;
  2227. };
  2228. // Operators
  2229. /**
  2230. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2231. * Returns the Vector2.
  2232. */
  2233. Vector2.prototype.toArray = function (array, index) {
  2234. if (index === void 0) { index = 0; }
  2235. array[index] = this.x;
  2236. array[index + 1] = this.y;
  2237. return this;
  2238. };
  2239. /**
  2240. * Returns a new array with 2 elements : the Vector2 coordinates.
  2241. */
  2242. Vector2.prototype.asArray = function () {
  2243. var result = new Array();
  2244. this.toArray(result, 0);
  2245. return result;
  2246. };
  2247. /**
  2248. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2249. * Returns the updated Vector2.
  2250. */
  2251. Vector2.prototype.copyFrom = function (source) {
  2252. this.x = source.x;
  2253. this.y = source.y;
  2254. return this;
  2255. };
  2256. /**
  2257. * Sets the Vector2 coordinates with the passed floats.
  2258. * Returns the updated Vector2.
  2259. */
  2260. Vector2.prototype.copyFromFloats = function (x, y) {
  2261. this.x = x;
  2262. this.y = y;
  2263. return this;
  2264. };
  2265. /**
  2266. * Sets the Vector2 coordinates with the passed floats.
  2267. * Returns the updated Vector2.
  2268. */
  2269. Vector2.prototype.set = function (x, y) {
  2270. return this.copyFromFloats(x, y);
  2271. };
  2272. /**
  2273. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2274. */
  2275. Vector2.prototype.add = function (otherVector) {
  2276. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2277. };
  2278. /**
  2279. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2280. * Returns the Vector2.
  2281. */
  2282. Vector2.prototype.addToRef = function (otherVector, result) {
  2283. result.x = this.x + otherVector.x;
  2284. result.y = this.y + otherVector.y;
  2285. return this;
  2286. };
  2287. /**
  2288. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2289. * Returns the updated Vector2.
  2290. */
  2291. Vector2.prototype.addInPlace = function (otherVector) {
  2292. this.x += otherVector.x;
  2293. this.y += otherVector.y;
  2294. return this;
  2295. };
  2296. /**
  2297. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2298. */
  2299. Vector2.prototype.addVector3 = function (otherVector) {
  2300. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2301. };
  2302. /**
  2303. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2304. */
  2305. Vector2.prototype.subtract = function (otherVector) {
  2306. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2307. };
  2308. /**
  2309. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2310. * Returns the Vector2.
  2311. */
  2312. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2313. result.x = this.x - otherVector.x;
  2314. result.y = this.y - otherVector.y;
  2315. return this;
  2316. };
  2317. /**
  2318. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2319. * Returns the updated Vector2.
  2320. */
  2321. Vector2.prototype.subtractInPlace = function (otherVector) {
  2322. this.x -= otherVector.x;
  2323. this.y -= otherVector.y;
  2324. return this;
  2325. };
  2326. /**
  2327. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2328. * Returns the updated Vector2.
  2329. */
  2330. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2331. this.x *= otherVector.x;
  2332. this.y *= otherVector.y;
  2333. return this;
  2334. };
  2335. /**
  2336. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2337. */
  2338. Vector2.prototype.multiply = function (otherVector) {
  2339. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2340. };
  2341. /**
  2342. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2343. * Returns the Vector2.
  2344. */
  2345. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2346. result.x = this.x * otherVector.x;
  2347. result.y = this.y * otherVector.y;
  2348. return this;
  2349. };
  2350. /**
  2351. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2352. */
  2353. Vector2.prototype.multiplyByFloats = function (x, y) {
  2354. return new Vector2(this.x * x, this.y * y);
  2355. };
  2356. /**
  2357. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2358. */
  2359. Vector2.prototype.divide = function (otherVector) {
  2360. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2361. };
  2362. /**
  2363. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2364. * Returns the Vector2.
  2365. */
  2366. Vector2.prototype.divideToRef = function (otherVector, result) {
  2367. result.x = this.x / otherVector.x;
  2368. result.y = this.y / otherVector.y;
  2369. return this;
  2370. };
  2371. /**
  2372. * Divides the current Vector3 coordinates by the passed ones.
  2373. * Returns the updated Vector3.
  2374. */
  2375. Vector2.prototype.divideInPlace = function (otherVector) {
  2376. return this.divideToRef(otherVector, this);
  2377. };
  2378. /**
  2379. * Returns a new Vector2 with current Vector2 negated coordinates.
  2380. */
  2381. Vector2.prototype.negate = function () {
  2382. return new Vector2(-this.x, -this.y);
  2383. };
  2384. /**
  2385. * Multiply the Vector2 coordinates by scale.
  2386. * Returns the updated Vector2.
  2387. */
  2388. Vector2.prototype.scaleInPlace = function (scale) {
  2389. this.x *= scale;
  2390. this.y *= scale;
  2391. return this;
  2392. };
  2393. /**
  2394. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2395. */
  2396. Vector2.prototype.scale = function (scale) {
  2397. var result = new Vector2(0, 0);
  2398. this.scaleToRef(scale, result);
  2399. return result;
  2400. };
  2401. /**
  2402. * Scale the current Vector2 values by a factor to a given Vector2
  2403. * @param scale defines the scale factor
  2404. * @param result defines the Vector2 object where to store the result
  2405. * @returns the unmodified current Vector2
  2406. */
  2407. Vector2.prototype.scaleToRef = function (scale, result) {
  2408. result.x = this.x * scale;
  2409. result.y = this.y * scale;
  2410. return this;
  2411. };
  2412. /**
  2413. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2414. * @param scale defines the scale factor
  2415. * @param result defines the Vector2 object where to store the result
  2416. * @returns the unmodified current Vector2
  2417. */
  2418. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2419. result.x += this.x * scale;
  2420. result.y += this.y * scale;
  2421. return this;
  2422. };
  2423. /**
  2424. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2425. */
  2426. Vector2.prototype.equals = function (otherVector) {
  2427. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2428. };
  2429. /**
  2430. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2431. */
  2432. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2433. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2434. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2435. };
  2436. // Properties
  2437. /**
  2438. * Returns the vector length (float).
  2439. */
  2440. Vector2.prototype.length = function () {
  2441. return Math.sqrt(this.x * this.x + this.y * this.y);
  2442. };
  2443. /**
  2444. * Returns the vector squared length (float);
  2445. */
  2446. Vector2.prototype.lengthSquared = function () {
  2447. return (this.x * this.x + this.y * this.y);
  2448. };
  2449. // Methods
  2450. /**
  2451. * Normalize the vector.
  2452. * Returns the updated Vector2.
  2453. */
  2454. Vector2.prototype.normalize = function () {
  2455. var len = this.length();
  2456. if (len === 0)
  2457. return this;
  2458. var num = 1.0 / len;
  2459. this.x *= num;
  2460. this.y *= num;
  2461. return this;
  2462. };
  2463. /**
  2464. * Returns a new Vector2 copied from the Vector2.
  2465. */
  2466. Vector2.prototype.clone = function () {
  2467. return new Vector2(this.x, this.y);
  2468. };
  2469. // Statics
  2470. /**
  2471. * Returns a new Vector2(0, 0)
  2472. */
  2473. Vector2.Zero = function () {
  2474. return new Vector2(0, 0);
  2475. };
  2476. /**
  2477. * Returns a new Vector2(1, 1)
  2478. */
  2479. Vector2.One = function () {
  2480. return new Vector2(1, 1);
  2481. };
  2482. /**
  2483. * Returns a new Vector2 set from the passed index element of the passed array.
  2484. */
  2485. Vector2.FromArray = function (array, offset) {
  2486. if (offset === void 0) { offset = 0; }
  2487. return new Vector2(array[offset], array[offset + 1]);
  2488. };
  2489. /**
  2490. * Sets "result" from the passed index element of the passed array.
  2491. */
  2492. Vector2.FromArrayToRef = function (array, offset, result) {
  2493. result.x = array[offset];
  2494. result.y = array[offset + 1];
  2495. };
  2496. /**
  2497. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2498. */
  2499. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2500. var squared = amount * amount;
  2501. var cubed = amount * squared;
  2502. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2503. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2504. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2505. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2506. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2507. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2508. return new Vector2(x, y);
  2509. };
  2510. /**
  2511. * 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".
  2512. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2513. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2514. */
  2515. Vector2.Clamp = function (value, min, max) {
  2516. var x = value.x;
  2517. x = (x > max.x) ? max.x : x;
  2518. x = (x < min.x) ? min.x : x;
  2519. var y = value.y;
  2520. y = (y > max.y) ? max.y : y;
  2521. y = (y < min.y) ? min.y : y;
  2522. return new Vector2(x, y);
  2523. };
  2524. /**
  2525. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2526. */
  2527. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2528. var squared = amount * amount;
  2529. var cubed = amount * squared;
  2530. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2531. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2532. var part3 = (cubed - (2.0 * squared)) + amount;
  2533. var part4 = cubed - squared;
  2534. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2535. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2536. return new Vector2(x, y);
  2537. };
  2538. /**
  2539. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2540. */
  2541. Vector2.Lerp = function (start, end, amount) {
  2542. var x = start.x + ((end.x - start.x) * amount);
  2543. var y = start.y + ((end.y - start.y) * amount);
  2544. return new Vector2(x, y);
  2545. };
  2546. /**
  2547. * Returns the dot product (float) of the vector "left" and the vector "right".
  2548. */
  2549. Vector2.Dot = function (left, right) {
  2550. return left.x * right.x + left.y * right.y;
  2551. };
  2552. /**
  2553. * Returns a new Vector2 equal to the normalized passed vector.
  2554. */
  2555. Vector2.Normalize = function (vector) {
  2556. var newVector = vector.clone();
  2557. newVector.normalize();
  2558. return newVector;
  2559. };
  2560. /**
  2561. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2562. */
  2563. Vector2.Minimize = function (left, right) {
  2564. var x = (left.x < right.x) ? left.x : right.x;
  2565. var y = (left.y < right.y) ? left.y : right.y;
  2566. return new Vector2(x, y);
  2567. };
  2568. /**
  2569. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2570. */
  2571. Vector2.Maximize = function (left, right) {
  2572. var x = (left.x > right.x) ? left.x : right.x;
  2573. var y = (left.y > right.y) ? left.y : right.y;
  2574. return new Vector2(x, y);
  2575. };
  2576. /**
  2577. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2578. */
  2579. Vector2.Transform = function (vector, transformation) {
  2580. var r = Vector2.Zero();
  2581. Vector2.TransformToRef(vector, transformation, r);
  2582. return r;
  2583. };
  2584. /**
  2585. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2586. */
  2587. Vector2.TransformToRef = function (vector, transformation, result) {
  2588. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2589. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2590. result.x = x;
  2591. result.y = y;
  2592. };
  2593. /**
  2594. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2595. */
  2596. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2597. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2598. var sign = a < 0 ? -1 : 1;
  2599. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2600. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2601. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2602. };
  2603. /**
  2604. * Returns the distance (float) between the vectors "value1" and "value2".
  2605. */
  2606. Vector2.Distance = function (value1, value2) {
  2607. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2608. };
  2609. /**
  2610. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2611. */
  2612. Vector2.DistanceSquared = function (value1, value2) {
  2613. var x = value1.x - value2.x;
  2614. var y = value1.y - value2.y;
  2615. return (x * x) + (y * y);
  2616. };
  2617. /**
  2618. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2619. */
  2620. Vector2.Center = function (value1, value2) {
  2621. var center = value1.add(value2);
  2622. center.scaleInPlace(0.5);
  2623. return center;
  2624. };
  2625. /**
  2626. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2627. */
  2628. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2629. var l2 = Vector2.DistanceSquared(segA, segB);
  2630. if (l2 === 0.0) {
  2631. return Vector2.Distance(p, segA);
  2632. }
  2633. var v = segB.subtract(segA);
  2634. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2635. var proj = segA.add(v.multiplyByFloats(t, t));
  2636. return Vector2.Distance(p, proj);
  2637. };
  2638. return Vector2;
  2639. }());
  2640. BABYLON.Vector2 = Vector2;
  2641. /**
  2642. * Classed used to store (x,y,z) vector representation
  2643. * A Vector3 is the main object used in 3D geometry
  2644. * It can represent etiher the coordinates of a point the space, either a direction
  2645. * Reminder: Babylon.js uses a left handed forward facing system
  2646. */
  2647. var Vector3 = /** @class */ (function () {
  2648. /**
  2649. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2650. * @param x defines the first coordinates (on X axis)
  2651. * @param y defines the second coordinates (on Y axis)
  2652. * @param z defines the third coordinates (on Z axis)
  2653. */
  2654. function Vector3(
  2655. /**
  2656. * Defines the first coordinates (on X axis)
  2657. */
  2658. x,
  2659. /**
  2660. * Defines the second coordinates (on Y axis)
  2661. */
  2662. y,
  2663. /**
  2664. * Defines the third coordinates (on Z axis)
  2665. */
  2666. z) {
  2667. this.x = x;
  2668. this.y = y;
  2669. this.z = z;
  2670. }
  2671. /**
  2672. * Creates a string representation of the Vector3
  2673. * @returns a string with the Vector3 coordinates.
  2674. */
  2675. Vector3.prototype.toString = function () {
  2676. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2677. };
  2678. /**
  2679. * Gets the class name
  2680. * @returns the string "Vector3"
  2681. */
  2682. Vector3.prototype.getClassName = function () {
  2683. return "Vector3";
  2684. };
  2685. /**
  2686. * Creates the Vector3 hash code
  2687. * @returns a number which tends to be unique between Vector3 instances
  2688. */
  2689. Vector3.prototype.getHashCode = function () {
  2690. var hash = this.x || 0;
  2691. hash = (hash * 397) ^ (this.y || 0);
  2692. hash = (hash * 397) ^ (this.z || 0);
  2693. return hash;
  2694. };
  2695. // Operators
  2696. /**
  2697. * Creates an array containing three elements : the coordinates of the Vector3
  2698. * @returns a new array of numbers
  2699. */
  2700. Vector3.prototype.asArray = function () {
  2701. var result = [];
  2702. this.toArray(result, 0);
  2703. return result;
  2704. };
  2705. /**
  2706. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2707. * @param array defines the destination array
  2708. * @param index defines the offset in the destination array
  2709. * @returns the current Vector3
  2710. */
  2711. Vector3.prototype.toArray = function (array, index) {
  2712. if (index === void 0) { index = 0; }
  2713. array[index] = this.x;
  2714. array[index + 1] = this.y;
  2715. array[index + 2] = this.z;
  2716. return this;
  2717. };
  2718. /**
  2719. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2720. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2721. */
  2722. Vector3.prototype.toQuaternion = function () {
  2723. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2724. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2725. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2726. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2727. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2728. var cosy = Math.cos(this.y * 0.5);
  2729. var siny = Math.sin(this.y * 0.5);
  2730. result.x = coszMinusx * siny;
  2731. result.y = -sinzMinusx * siny;
  2732. result.z = sinxPlusz * cosy;
  2733. result.w = cosxPlusz * cosy;
  2734. return result;
  2735. };
  2736. /**
  2737. * Adds the passed vector to the current Vector3
  2738. * @param otherVector defines the second operand
  2739. * @returns the current updated Vector3
  2740. */
  2741. Vector3.prototype.addInPlace = function (otherVector) {
  2742. this.x += otherVector.x;
  2743. this.y += otherVector.y;
  2744. this.z += otherVector.z;
  2745. return this;
  2746. };
  2747. /**
  2748. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2749. * @param otherVector defines the second operand
  2750. * @returns the resulting Vector3
  2751. */
  2752. Vector3.prototype.add = function (otherVector) {
  2753. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2754. };
  2755. /**
  2756. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2757. * @param otherVector defines the second operand
  2758. * @param result defines the Vector3 object where to store the result
  2759. * @returns the current Vector3
  2760. */
  2761. Vector3.prototype.addToRef = function (otherVector, result) {
  2762. result.x = this.x + otherVector.x;
  2763. result.y = this.y + otherVector.y;
  2764. result.z = this.z + otherVector.z;
  2765. return this;
  2766. };
  2767. /**
  2768. * Subtract the passed vector from the current Vector3
  2769. * @param otherVector defines the second operand
  2770. * @returns the current updated Vector3
  2771. */
  2772. Vector3.prototype.subtractInPlace = function (otherVector) {
  2773. this.x -= otherVector.x;
  2774. this.y -= otherVector.y;
  2775. this.z -= otherVector.z;
  2776. return this;
  2777. };
  2778. /**
  2779. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2780. * @param otherVector defines the second operand
  2781. * @returns the resulting Vector3
  2782. */
  2783. Vector3.prototype.subtract = function (otherVector) {
  2784. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2785. };
  2786. /**
  2787. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2788. * @param otherVector defines the second operand
  2789. * @param result defines the Vector3 object where to store the result
  2790. * @returns the current Vector3
  2791. */
  2792. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2793. result.x = this.x - otherVector.x;
  2794. result.y = this.y - otherVector.y;
  2795. result.z = this.z - otherVector.z;
  2796. return this;
  2797. };
  2798. /**
  2799. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2800. * @param x defines the x coordinate of the operand
  2801. * @param y defines the y coordinate of the operand
  2802. * @param z defines the z coordinate of the operand
  2803. * @returns the resulting Vector3
  2804. */
  2805. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2806. return new Vector3(this.x - x, this.y - y, this.z - z);
  2807. };
  2808. /**
  2809. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2810. * @param x defines the x coordinate of the operand
  2811. * @param y defines the y coordinate of the operand
  2812. * @param z defines the z coordinate of the operand
  2813. * @param result defines the Vector3 object where to store the result
  2814. * @returns the current Vector3
  2815. */
  2816. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2817. result.x = this.x - x;
  2818. result.y = this.y - y;
  2819. result.z = this.z - z;
  2820. return this;
  2821. };
  2822. /**
  2823. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2824. * @returns a new Vector3
  2825. */
  2826. Vector3.prototype.negate = function () {
  2827. return new Vector3(-this.x, -this.y, -this.z);
  2828. };
  2829. /**
  2830. * Multiplies the Vector3 coordinates by the float "scale"
  2831. * @param scale defines the multiplier factor
  2832. * @returns the current updated Vector3
  2833. */
  2834. Vector3.prototype.scaleInPlace = function (scale) {
  2835. this.x *= scale;
  2836. this.y *= scale;
  2837. this.z *= scale;
  2838. return this;
  2839. };
  2840. /**
  2841. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2842. * @param scale defines the multiplier factor
  2843. * @returns a new Vector3
  2844. */
  2845. Vector3.prototype.scale = function (scale) {
  2846. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2847. };
  2848. /**
  2849. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2850. * @param scale defines the multiplier factor
  2851. * @param result defines the Vector3 object where to store the result
  2852. * @returns the current Vector3
  2853. */
  2854. Vector3.prototype.scaleToRef = function (scale, result) {
  2855. result.x = this.x * scale;
  2856. result.y = this.y * scale;
  2857. result.z = this.z * scale;
  2858. return this;
  2859. };
  2860. /**
  2861. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2862. * @param scale defines the scale factor
  2863. * @param result defines the Vector3 object where to store the result
  2864. * @returns the unmodified current Vector3
  2865. */
  2866. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2867. result.x += this.x * scale;
  2868. result.y += this.y * scale;
  2869. result.z += this.z * scale;
  2870. return this;
  2871. };
  2872. /**
  2873. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2874. * @param otherVector defines the second operand
  2875. * @returns true if both vectors are equals
  2876. */
  2877. Vector3.prototype.equals = function (otherVector) {
  2878. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2879. };
  2880. /**
  2881. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2882. * @param otherVector defines the second operand
  2883. * @param epsilon defines the minimal distance to define values as equals
  2884. * @returns true if both vectors are distant less than epsilon
  2885. */
  2886. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2887. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2888. 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);
  2889. };
  2890. /**
  2891. * Returns true if the current Vector3 coordinates equals the passed floats
  2892. * @param x defines the x coordinate of the operand
  2893. * @param y defines the y coordinate of the operand
  2894. * @param z defines the z coordinate of the operand
  2895. * @returns true if both vectors are equals
  2896. */
  2897. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2898. return this.x === x && this.y === y && this.z === z;
  2899. };
  2900. /**
  2901. * Multiplies the current Vector3 coordinates by the passed ones
  2902. * @param otherVector defines the second operand
  2903. * @returns the current updated Vector3
  2904. */
  2905. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2906. this.x *= otherVector.x;
  2907. this.y *= otherVector.y;
  2908. this.z *= otherVector.z;
  2909. return this;
  2910. };
  2911. /**
  2912. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2913. * @param otherVector defines the second operand
  2914. * @returns the new Vector3
  2915. */
  2916. Vector3.prototype.multiply = function (otherVector) {
  2917. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2918. };
  2919. /**
  2920. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  2921. * @param otherVector defines the second operand
  2922. * @param result defines the Vector3 object where to store the result
  2923. * @returns the current Vector3
  2924. */
  2925. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2926. result.x = this.x * otherVector.x;
  2927. result.y = this.y * otherVector.y;
  2928. result.z = this.z * otherVector.z;
  2929. return this;
  2930. };
  2931. /**
  2932. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  2933. * @param x defines the x coordinate of the operand
  2934. * @param y defines the y coordinate of the operand
  2935. * @param z defines the z coordinate of the operand
  2936. * @returns the new Vector3
  2937. */
  2938. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2939. return new Vector3(this.x * x, this.y * y, this.z * z);
  2940. };
  2941. /**
  2942. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  2943. * @param otherVector defines the second operand
  2944. * @returns the new Vector3
  2945. */
  2946. Vector3.prototype.divide = function (otherVector) {
  2947. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2948. };
  2949. /**
  2950. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  2951. * @param otherVector defines the second operand
  2952. * @param result defines the Vector3 object where to store the result
  2953. * @returns the current Vector3
  2954. */
  2955. Vector3.prototype.divideToRef = function (otherVector, result) {
  2956. result.x = this.x / otherVector.x;
  2957. result.y = this.y / otherVector.y;
  2958. result.z = this.z / otherVector.z;
  2959. return this;
  2960. };
  2961. /**
  2962. * Divides the current Vector3 coordinates by the passed ones.
  2963. * @param otherVector defines the second operand
  2964. * @returns the current updated Vector3
  2965. */
  2966. Vector3.prototype.divideInPlace = function (otherVector) {
  2967. return this.divideToRef(otherVector, this);
  2968. };
  2969. /**
  2970. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  2971. * @param other defines the second operand
  2972. * @returns the current updated Vector3
  2973. */
  2974. Vector3.prototype.minimizeInPlace = function (other) {
  2975. if (other.x < this.x)
  2976. this.x = other.x;
  2977. if (other.y < this.y)
  2978. this.y = other.y;
  2979. if (other.z < this.z)
  2980. this.z = other.z;
  2981. return this;
  2982. };
  2983. /**
  2984. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2985. * @param other defines the second operand
  2986. * @returns the current updated Vector3
  2987. */
  2988. Vector3.prototype.maximizeInPlace = function (other) {
  2989. if (other.x > this.x)
  2990. this.x = other.x;
  2991. if (other.y > this.y)
  2992. this.y = other.y;
  2993. if (other.z > this.z)
  2994. this.z = other.z;
  2995. return this;
  2996. };
  2997. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2998. /**
  2999. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3000. */
  3001. get: function () {
  3002. var absX = Math.abs(this.x);
  3003. var absY = Math.abs(this.y);
  3004. if (absX !== absY) {
  3005. return true;
  3006. }
  3007. var absZ = Math.abs(this.z);
  3008. if (absX !== absZ) {
  3009. return true;
  3010. }
  3011. if (absY !== absZ) {
  3012. return true;
  3013. }
  3014. return false;
  3015. },
  3016. enumerable: true,
  3017. configurable: true
  3018. });
  3019. // Properties
  3020. /**
  3021. * Gets the length of the Vector3
  3022. * @returns the length of the Vecto3
  3023. */
  3024. Vector3.prototype.length = function () {
  3025. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3026. };
  3027. /**
  3028. * Gets the squared length of the Vector3
  3029. * @returns squared length of the Vector3
  3030. */
  3031. Vector3.prototype.lengthSquared = function () {
  3032. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3033. };
  3034. /**
  3035. * Normalize the current Vector3.
  3036. * Please note that this is an in place operation.
  3037. * @returns the current updated Vector3
  3038. */
  3039. Vector3.prototype.normalize = function () {
  3040. var len = this.length();
  3041. if (len === 0 || len === 1.0)
  3042. return this;
  3043. var num = 1.0 / len;
  3044. this.x *= num;
  3045. this.y *= num;
  3046. this.z *= num;
  3047. return this;
  3048. };
  3049. /**
  3050. * Normalize the current Vector3 to a new vector
  3051. * @returns the new Vector3
  3052. */
  3053. Vector3.prototype.normalizeToNew = function () {
  3054. var normalized = new Vector3(0, 0, 0);
  3055. this.normalizeToRef(normalized);
  3056. return normalized;
  3057. };
  3058. /**
  3059. * Normalize the current Vector3 to the reference
  3060. * @param reference define the Vector3 to update
  3061. * @returns the updated Vector3
  3062. */
  3063. Vector3.prototype.normalizeToRef = function (reference) {
  3064. var len = this.length();
  3065. if (len === 0 || len === 1.0) {
  3066. reference.set(this.x, this.y, this.z);
  3067. return reference;
  3068. }
  3069. var scale = 1.0 / len;
  3070. this.scaleToRef(scale, reference);
  3071. return reference;
  3072. };
  3073. /**
  3074. * Creates a new Vector3 copied from the current Vector3
  3075. * @returns the new Vector3
  3076. */
  3077. Vector3.prototype.clone = function () {
  3078. return new Vector3(this.x, this.y, this.z);
  3079. };
  3080. /**
  3081. * Copies the passed vector coordinates to the current Vector3 ones
  3082. * @param source defines the source Vector3
  3083. * @returns the current updated Vector3
  3084. */
  3085. Vector3.prototype.copyFrom = function (source) {
  3086. this.x = source.x;
  3087. this.y = source.y;
  3088. this.z = source.z;
  3089. return this;
  3090. };
  3091. /**
  3092. * Copies the passed floats to the current Vector3 coordinates
  3093. * @param x defines the x coordinate of the operand
  3094. * @param y defines the y coordinate of the operand
  3095. * @param z defines the z coordinate of the operand
  3096. * @returns the current updated Vector3
  3097. */
  3098. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3099. this.x = x;
  3100. this.y = y;
  3101. this.z = z;
  3102. return this;
  3103. };
  3104. /**
  3105. * Copies the passed floats to the current Vector3 coordinates
  3106. * @param x defines the x coordinate of the operand
  3107. * @param y defines the y coordinate of the operand
  3108. * @param z defines the z coordinate of the operand
  3109. * @returns the current updated Vector3
  3110. */
  3111. Vector3.prototype.set = function (x, y, z) {
  3112. return this.copyFromFloats(x, y, z);
  3113. };
  3114. // Statics
  3115. /**
  3116. * Get the clip factor between two vectors
  3117. * @param vector0 defines the first operand
  3118. * @param vector1 defines the second operand
  3119. * @param axis defines the axis to use
  3120. * @param size defines the size along the axis
  3121. * @returns the clip factor
  3122. */
  3123. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3124. var d0 = Vector3.Dot(vector0, axis) - size;
  3125. var d1 = Vector3.Dot(vector1, axis) - size;
  3126. var s = d0 / (d0 - d1);
  3127. return s;
  3128. };
  3129. /**
  3130. * Get angle between two vectors
  3131. * @param vector0 angle between vector0 and vector1
  3132. * @param vector1 angle between vector0 and vector1
  3133. * @param normal direction of the normal
  3134. * @return the angle between vector0 and vector1
  3135. */
  3136. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3137. var v0 = vector0.clone().normalize();
  3138. var v1 = vector1.clone().normalize();
  3139. var dot = Vector3.Dot(v0, v1);
  3140. var n = Vector3.Cross(v0, v1);
  3141. if (Vector3.Dot(n, normal) > 0) {
  3142. return Math.acos(dot);
  3143. }
  3144. return -Math.acos(dot);
  3145. };
  3146. /**
  3147. * Returns a new Vector3 set from the index "offset" of the passed array
  3148. * @param array defines the source array
  3149. * @param offset defines the offset in the source array
  3150. * @returns the new Vector3
  3151. */
  3152. Vector3.FromArray = function (array, offset) {
  3153. if (!offset) {
  3154. offset = 0;
  3155. }
  3156. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3157. };
  3158. /**
  3159. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3160. * This function is deprecated. Use FromArray instead
  3161. * @param array defines the source array
  3162. * @param offset defines the offset in the source array
  3163. * @returns the new Vector3
  3164. */
  3165. Vector3.FromFloatArray = function (array, offset) {
  3166. return Vector3.FromArray(array, offset);
  3167. };
  3168. /**
  3169. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3170. * @param array defines the source array
  3171. * @param offset defines the offset in the source array
  3172. * @param result defines the Vector3 where to store the result
  3173. */
  3174. Vector3.FromArrayToRef = function (array, offset, result) {
  3175. result.x = array[offset];
  3176. result.y = array[offset + 1];
  3177. result.z = array[offset + 2];
  3178. };
  3179. /**
  3180. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3181. * This function is deprecated. Use FromArrayToRef instead.
  3182. * @param array defines the source array
  3183. * @param offset defines the offset in the source array
  3184. * @param result defines the Vector3 where to store the result
  3185. */
  3186. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3187. return Vector3.FromArrayToRef(array, offset, result);
  3188. };
  3189. /**
  3190. * Sets the passed vector "result" with the passed floats.
  3191. * @param x defines the x coordinate of the source
  3192. * @param y defines the y coordinate of the source
  3193. * @param z defines the z coordinate of the source
  3194. * @param result defines the Vector3 where to store the result
  3195. */
  3196. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3197. result.x = x;
  3198. result.y = y;
  3199. result.z = z;
  3200. };
  3201. /**
  3202. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3203. * @returns a new empty Vector3
  3204. */
  3205. Vector3.Zero = function () {
  3206. return new Vector3(0.0, 0.0, 0.0);
  3207. };
  3208. /**
  3209. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3210. * @returns a new unit Vector3
  3211. */
  3212. Vector3.One = function () {
  3213. return new Vector3(1.0, 1.0, 1.0);
  3214. };
  3215. /**
  3216. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3217. * @returns a new up Vector3
  3218. */
  3219. Vector3.Up = function () {
  3220. return new Vector3(0.0, 1.0, 0.0);
  3221. };
  3222. /**
  3223. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3224. * @returns a new forward Vector3
  3225. */
  3226. Vector3.Forward = function () {
  3227. return new Vector3(0.0, 0.0, 1.0);
  3228. };
  3229. /**
  3230. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3231. * @returns a new right Vector3
  3232. */
  3233. Vector3.Right = function () {
  3234. return new Vector3(1.0, 0.0, 0.0);
  3235. };
  3236. /**
  3237. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3238. * @returns a new left Vector3
  3239. */
  3240. Vector3.Left = function () {
  3241. return new Vector3(-1.0, 0.0, 0.0);
  3242. };
  3243. /**
  3244. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3245. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3246. * @param vector defines the Vector3 to transform
  3247. * @param transformation defines the transformation matrix
  3248. * @returns the transformed Vector3
  3249. */
  3250. Vector3.TransformCoordinates = function (vector, transformation) {
  3251. var result = Vector3.Zero();
  3252. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3253. return result;
  3254. };
  3255. /**
  3256. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3257. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3258. * @param vector defines the Vector3 to transform
  3259. * @param transformation defines the transformation matrix
  3260. * @param result defines the Vector3 where to store the result
  3261. */
  3262. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3263. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3264. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3265. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3266. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3267. result.x = x / w;
  3268. result.y = y / w;
  3269. result.z = z / w;
  3270. };
  3271. /**
  3272. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3273. * This method computes tranformed coordinates only, not transformed direction vectors
  3274. * @param x define the x coordinate of the source vector
  3275. * @param y define the y coordinate of the source vector
  3276. * @param z define the z coordinate of the source vector
  3277. * @param transformation defines the transformation matrix
  3278. * @param result defines the Vector3 where to store the result
  3279. */
  3280. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3281. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3282. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3283. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3284. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3285. result.x = rx / rw;
  3286. result.y = ry / rw;
  3287. result.z = rz / rw;
  3288. };
  3289. /**
  3290. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3291. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3292. * @param vector defines the Vector3 to transform
  3293. * @param transformation defines the transformation matrix
  3294. * @returns the new Vector3
  3295. */
  3296. Vector3.TransformNormal = function (vector, transformation) {
  3297. var result = Vector3.Zero();
  3298. Vector3.TransformNormalToRef(vector, transformation, result);
  3299. return result;
  3300. };
  3301. /**
  3302. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3303. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3304. * @param vector defines the Vector3 to transform
  3305. * @param transformation defines the transformation matrix
  3306. * @param result defines the Vector3 where to store the result
  3307. */
  3308. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3309. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3310. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3311. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3312. result.x = x;
  3313. result.y = y;
  3314. result.z = z;
  3315. };
  3316. /**
  3317. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3318. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3319. * @param x define the x coordinate of the source vector
  3320. * @param y define the y coordinate of the source vector
  3321. * @param z define the z coordinate of the source vector
  3322. * @param transformation defines the transformation matrix
  3323. * @param result defines the Vector3 where to store the result
  3324. */
  3325. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3326. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3327. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3328. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3329. };
  3330. /**
  3331. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3332. * @param value1 defines the first control point
  3333. * @param value2 defines the second control point
  3334. * @param value3 defines the third control point
  3335. * @param value4 defines the fourth control point
  3336. * @param amount defines the amount on the spline to use
  3337. * @returns the new Vector3
  3338. */
  3339. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3340. var squared = amount * amount;
  3341. var cubed = amount * squared;
  3342. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3343. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3344. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3345. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3346. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3347. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3348. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3349. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3350. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3351. return new Vector3(x, y, z);
  3352. };
  3353. /**
  3354. * 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"
  3355. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3356. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3357. * @param value defines the current value
  3358. * @param min defines the lower range value
  3359. * @param max defines the upper range value
  3360. * @returns the new Vector3
  3361. */
  3362. Vector3.Clamp = function (value, min, max) {
  3363. var x = value.x;
  3364. x = (x > max.x) ? max.x : x;
  3365. x = (x < min.x) ? min.x : x;
  3366. var y = value.y;
  3367. y = (y > max.y) ? max.y : y;
  3368. y = (y < min.y) ? min.y : y;
  3369. var z = value.z;
  3370. z = (z > max.z) ? max.z : z;
  3371. z = (z < min.z) ? min.z : z;
  3372. return new Vector3(x, y, z);
  3373. };
  3374. /**
  3375. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3376. * @param value1 defines the first control point
  3377. * @param tangent1 defines the first tangent vector
  3378. * @param value2 defines the second control point
  3379. * @param tangent2 defines the second tangent vector
  3380. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3381. * @returns the new Vector3
  3382. */
  3383. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3384. var squared = amount * amount;
  3385. var cubed = amount * squared;
  3386. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3387. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3388. var part3 = (cubed - (2.0 * squared)) + amount;
  3389. var part4 = cubed - squared;
  3390. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3391. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3392. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3393. return new Vector3(x, y, z);
  3394. };
  3395. /**
  3396. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3397. * @param start defines the start value
  3398. * @param end defines the end value
  3399. * @param amount max defines amount between both (between 0 and 1)
  3400. * @returns the new Vector3
  3401. */
  3402. Vector3.Lerp = function (start, end, amount) {
  3403. var result = new Vector3(0, 0, 0);
  3404. Vector3.LerpToRef(start, end, amount, result);
  3405. return result;
  3406. };
  3407. /**
  3408. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3409. * @param start defines the start value
  3410. * @param end defines the end value
  3411. * @param amount max defines amount between both (between 0 and 1)
  3412. * @param result defines the Vector3 where to store the result
  3413. */
  3414. Vector3.LerpToRef = function (start, end, amount, result) {
  3415. result.x = start.x + ((end.x - start.x) * amount);
  3416. result.y = start.y + ((end.y - start.y) * amount);
  3417. result.z = start.z + ((end.z - start.z) * amount);
  3418. };
  3419. /**
  3420. * Returns the dot product (float) between the vectors "left" and "right"
  3421. * @param left defines the left operand
  3422. * @param right defines the right operand
  3423. * @returns the dot product
  3424. */
  3425. Vector3.Dot = function (left, right) {
  3426. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3427. };
  3428. /**
  3429. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3430. * The cross product is then orthogonal to both "left" and "right"
  3431. * @param left defines the left operand
  3432. * @param right defines the right operand
  3433. * @returns the cross product
  3434. */
  3435. Vector3.Cross = function (left, right) {
  3436. var result = Vector3.Zero();
  3437. Vector3.CrossToRef(left, right, result);
  3438. return result;
  3439. };
  3440. /**
  3441. * Sets the passed vector "result" with the cross product of "left" and "right"
  3442. * The cross product is then orthogonal to both "left" and "right"
  3443. * @param left defines the left operand
  3444. * @param right defines the right operand
  3445. * @param result defines the Vector3 where to store the result
  3446. */
  3447. Vector3.CrossToRef = function (left, right, result) {
  3448. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3449. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3450. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3451. result.copyFrom(MathTmp.Vector3[0]);
  3452. };
  3453. /**
  3454. * Returns a new Vector3 as the normalization of the passed vector
  3455. * @param vector defines the Vector3 to normalize
  3456. * @returns the new Vector3
  3457. */
  3458. Vector3.Normalize = function (vector) {
  3459. var result = Vector3.Zero();
  3460. Vector3.NormalizeToRef(vector, result);
  3461. return result;
  3462. };
  3463. /**
  3464. * Sets the passed vector "result" with the normalization of the passed first vector
  3465. * @param vector defines the Vector3 to normalize
  3466. * @param result defines the Vector3 where to store the result
  3467. */
  3468. Vector3.NormalizeToRef = function (vector, result) {
  3469. result.copyFrom(vector);
  3470. result.normalize();
  3471. };
  3472. /**
  3473. * Project a Vector3 onto screen space
  3474. * @param vector defines the Vector3 to project
  3475. * @param world defines the world matrix to use
  3476. * @param transform defines the transform (view x projection) matrix to use
  3477. * @param viewport defines the screen viewport to use
  3478. * @returns the new Vector3
  3479. */
  3480. Vector3.Project = function (vector, world, transform, viewport) {
  3481. var cw = viewport.width;
  3482. var ch = viewport.height;
  3483. var cx = viewport.x;
  3484. var cy = viewport.y;
  3485. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3486. 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);
  3487. var matrix = MathTmp.Matrix[0];
  3488. world.multiplyToRef(transform, matrix);
  3489. matrix.multiplyToRef(viewportMatrix, matrix);
  3490. return Vector3.TransformCoordinates(vector, matrix);
  3491. };
  3492. /**
  3493. * Unproject from screen space to object space
  3494. * @param source defines the screen space Vector3 to use
  3495. * @param viewportWidth defines the current width of the viewport
  3496. * @param viewportHeight defines the current height of the viewport
  3497. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3498. * @param transform defines the transform (view x projection) matrix to use
  3499. * @returns the new Vector3
  3500. */
  3501. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3502. var matrix = MathTmp.Matrix[0];
  3503. world.multiplyToRef(transform, matrix);
  3504. matrix.invert();
  3505. source.x = source.x / viewportWidth * 2 - 1;
  3506. source.y = -(source.y / viewportHeight * 2 - 1);
  3507. var vector = Vector3.TransformCoordinates(source, matrix);
  3508. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3509. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3510. vector = vector.scale(1.0 / num);
  3511. }
  3512. return vector;
  3513. };
  3514. /**
  3515. * Unproject from screen space to object space
  3516. * @param source defines the screen space Vector3 to use
  3517. * @param viewportWidth defines the current width of the viewport
  3518. * @param viewportHeight defines the current height of the viewport
  3519. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3520. * @param view defines the view matrix to use
  3521. * @param projection defines the projection matrix to use
  3522. * @returns the new Vector3
  3523. */
  3524. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3525. var result = Vector3.Zero();
  3526. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3527. return result;
  3528. };
  3529. /**
  3530. * Unproject from screen space to object space
  3531. * @param source defines the screen space Vector3 to use
  3532. * @param viewportWidth defines the current width of the viewport
  3533. * @param viewportHeight defines the current height of the viewport
  3534. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3535. * @param view defines the view matrix to use
  3536. * @param projection defines the projection matrix to use
  3537. * @param result defines the Vector3 where to store the result
  3538. */
  3539. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3540. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3541. };
  3542. /**
  3543. * Unproject from screen space to object space
  3544. * @param sourceX defines the screen space x coordinate to use
  3545. * @param sourceY defines the screen space y coordinate to use
  3546. * @param sourceZ defines the screen space z coordinate to use
  3547. * @param viewportWidth defines the current width of the viewport
  3548. * @param viewportHeight defines the current height of the viewport
  3549. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3550. * @param view defines the view matrix to use
  3551. * @param projection defines the projection matrix to use
  3552. * @param result defines the Vector3 where to store the result
  3553. */
  3554. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3555. var matrix = MathTmp.Matrix[0];
  3556. world.multiplyToRef(view, matrix);
  3557. matrix.multiplyToRef(projection, matrix);
  3558. matrix.invert();
  3559. var screenSource = MathTmp.Vector3[0];
  3560. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3561. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3562. screenSource.z = 2 * sourceZ - 1.0;
  3563. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3564. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3565. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3566. result.scaleInPlace(1.0 / num);
  3567. }
  3568. };
  3569. /**
  3570. * Gets the minimal coordinate values between two Vector3
  3571. * @param left defines the first operand
  3572. * @param right defines the second operand
  3573. * @returns the new Vector3
  3574. */
  3575. Vector3.Minimize = function (left, right) {
  3576. var min = left.clone();
  3577. min.minimizeInPlace(right);
  3578. return min;
  3579. };
  3580. /**
  3581. * Gets the maximal coordinate values between two Vector3
  3582. * @param left defines the first operand
  3583. * @param right defines the second operand
  3584. * @returns the new Vector3
  3585. */
  3586. Vector3.Maximize = function (left, right) {
  3587. var max = left.clone();
  3588. max.maximizeInPlace(right);
  3589. return max;
  3590. };
  3591. /**
  3592. * Returns the distance between the vectors "value1" and "value2"
  3593. * @param value1 defines the first operand
  3594. * @param value2 defines the second operand
  3595. * @returns the distance
  3596. */
  3597. Vector3.Distance = function (value1, value2) {
  3598. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3599. };
  3600. /**
  3601. * Returns the squared distance between the vectors "value1" and "value2"
  3602. * @param value1 defines the first operand
  3603. * @param value2 defines the second operand
  3604. * @returns the squared distance
  3605. */
  3606. Vector3.DistanceSquared = function (value1, value2) {
  3607. var x = value1.x - value2.x;
  3608. var y = value1.y - value2.y;
  3609. var z = value1.z - value2.z;
  3610. return (x * x) + (y * y) + (z * z);
  3611. };
  3612. /**
  3613. * Returns a new Vector3 located at the center between "value1" and "value2"
  3614. * @param value1 defines the first operand
  3615. * @param value2 defines the second operand
  3616. * @returns the new Vector3
  3617. */
  3618. Vector3.Center = function (value1, value2) {
  3619. var center = value1.add(value2);
  3620. center.scaleInPlace(0.5);
  3621. return center;
  3622. };
  3623. /**
  3624. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3625. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3626. * to something in order to rotate it from its local system to the given target system
  3627. * Note: axis1, axis2 and axis3 are normalized during this operation
  3628. * @param axis1 defines the first axis
  3629. * @param axis2 defines the second axis
  3630. * @param axis3 defines the third axis
  3631. * @returns a new Vector3
  3632. */
  3633. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3634. var rotation = Vector3.Zero();
  3635. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3636. return rotation;
  3637. };
  3638. /**
  3639. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3640. * @param axis1 defines the first axis
  3641. * @param axis2 defines the second axis
  3642. * @param axis3 defines the third axis
  3643. * @param ref defines the Vector3 where to store the result
  3644. */
  3645. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3646. var quat = MathTmp.Quaternion[0];
  3647. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3648. quat.toEulerAnglesToRef(ref);
  3649. };
  3650. return Vector3;
  3651. }());
  3652. BABYLON.Vector3 = Vector3;
  3653. //Vector4 class created for EulerAngle class conversion to Quaternion
  3654. var Vector4 = /** @class */ (function () {
  3655. /**
  3656. * Creates a Vector4 object from the passed floats.
  3657. */
  3658. function Vector4(x, y, z, w) {
  3659. this.x = x;
  3660. this.y = y;
  3661. this.z = z;
  3662. this.w = w;
  3663. }
  3664. /**
  3665. * Returns the string with the Vector4 coordinates.
  3666. */
  3667. Vector4.prototype.toString = function () {
  3668. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3669. };
  3670. /**
  3671. * Returns the string "Vector4".
  3672. */
  3673. Vector4.prototype.getClassName = function () {
  3674. return "Vector4";
  3675. };
  3676. /**
  3677. * Returns the Vector4 hash code.
  3678. */
  3679. Vector4.prototype.getHashCode = function () {
  3680. var hash = this.x || 0;
  3681. hash = (hash * 397) ^ (this.y || 0);
  3682. hash = (hash * 397) ^ (this.z || 0);
  3683. hash = (hash * 397) ^ (this.w || 0);
  3684. return hash;
  3685. };
  3686. // Operators
  3687. /**
  3688. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3689. */
  3690. Vector4.prototype.asArray = function () {
  3691. var result = new Array();
  3692. this.toArray(result, 0);
  3693. return result;
  3694. };
  3695. /**
  3696. * Populates the passed array from the passed index with the Vector4 coordinates.
  3697. * Returns the Vector4.
  3698. */
  3699. Vector4.prototype.toArray = function (array, index) {
  3700. if (index === undefined) {
  3701. index = 0;
  3702. }
  3703. array[index] = this.x;
  3704. array[index + 1] = this.y;
  3705. array[index + 2] = this.z;
  3706. array[index + 3] = this.w;
  3707. return this;
  3708. };
  3709. /**
  3710. * Adds the passed vector to the current Vector4.
  3711. * Returns the updated Vector4.
  3712. */
  3713. Vector4.prototype.addInPlace = function (otherVector) {
  3714. this.x += otherVector.x;
  3715. this.y += otherVector.y;
  3716. this.z += otherVector.z;
  3717. this.w += otherVector.w;
  3718. return this;
  3719. };
  3720. /**
  3721. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3722. */
  3723. Vector4.prototype.add = function (otherVector) {
  3724. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3725. };
  3726. /**
  3727. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3728. * Returns the current Vector4.
  3729. */
  3730. Vector4.prototype.addToRef = function (otherVector, result) {
  3731. result.x = this.x + otherVector.x;
  3732. result.y = this.y + otherVector.y;
  3733. result.z = this.z + otherVector.z;
  3734. result.w = this.w + otherVector.w;
  3735. return this;
  3736. };
  3737. /**
  3738. * Subtract in place the passed vector from the current Vector4.
  3739. * Returns the updated Vector4.
  3740. */
  3741. Vector4.prototype.subtractInPlace = function (otherVector) {
  3742. this.x -= otherVector.x;
  3743. this.y -= otherVector.y;
  3744. this.z -= otherVector.z;
  3745. this.w -= otherVector.w;
  3746. return this;
  3747. };
  3748. /**
  3749. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3750. */
  3751. Vector4.prototype.subtract = function (otherVector) {
  3752. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3753. };
  3754. /**
  3755. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3756. * Returns the current Vector4.
  3757. */
  3758. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3759. result.x = this.x - otherVector.x;
  3760. result.y = this.y - otherVector.y;
  3761. result.z = this.z - otherVector.z;
  3762. result.w = this.w - otherVector.w;
  3763. return this;
  3764. };
  3765. /**
  3766. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3767. */
  3768. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3769. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3770. };
  3771. /**
  3772. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3773. * Returns the current Vector4.
  3774. */
  3775. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3776. result.x = this.x - x;
  3777. result.y = this.y - y;
  3778. result.z = this.z - z;
  3779. result.w = this.w - w;
  3780. return this;
  3781. };
  3782. /**
  3783. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3784. */
  3785. Vector4.prototype.negate = function () {
  3786. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3787. };
  3788. /**
  3789. * Multiplies the current Vector4 coordinates by scale (float).
  3790. * Returns the updated Vector4.
  3791. */
  3792. Vector4.prototype.scaleInPlace = function (scale) {
  3793. this.x *= scale;
  3794. this.y *= scale;
  3795. this.z *= scale;
  3796. this.w *= scale;
  3797. return this;
  3798. };
  3799. /**
  3800. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3801. */
  3802. Vector4.prototype.scale = function (scale) {
  3803. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3804. };
  3805. /**
  3806. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3807. * Returns the current Vector4.
  3808. */
  3809. Vector4.prototype.scaleToRef = function (scale, result) {
  3810. result.x = this.x * scale;
  3811. result.y = this.y * scale;
  3812. result.z = this.z * scale;
  3813. result.w = this.w * scale;
  3814. return this;
  3815. };
  3816. /**
  3817. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3818. * @param scale defines the scale factor
  3819. * @param result defines the Vector4 object where to store the result
  3820. * @returns the unmodified current Vector4
  3821. */
  3822. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3823. result.x += this.x * scale;
  3824. result.y += this.y * scale;
  3825. result.z += this.z * scale;
  3826. result.w += this.w * scale;
  3827. return this;
  3828. };
  3829. /**
  3830. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3831. */
  3832. Vector4.prototype.equals = function (otherVector) {
  3833. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3834. };
  3835. /**
  3836. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3837. */
  3838. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3839. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3840. return otherVector
  3841. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3842. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3843. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3844. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3845. };
  3846. /**
  3847. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3848. */
  3849. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3850. return this.x === x && this.y === y && this.z === z && this.w === w;
  3851. };
  3852. /**
  3853. * Multiplies in place the current Vector4 by the passed one.
  3854. * Returns the updated Vector4.
  3855. */
  3856. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3857. this.x *= otherVector.x;
  3858. this.y *= otherVector.y;
  3859. this.z *= otherVector.z;
  3860. this.w *= otherVector.w;
  3861. return this;
  3862. };
  3863. /**
  3864. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3865. */
  3866. Vector4.prototype.multiply = function (otherVector) {
  3867. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3868. };
  3869. /**
  3870. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3871. * Returns the current Vector4.
  3872. */
  3873. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3874. result.x = this.x * otherVector.x;
  3875. result.y = this.y * otherVector.y;
  3876. result.z = this.z * otherVector.z;
  3877. result.w = this.w * otherVector.w;
  3878. return this;
  3879. };
  3880. /**
  3881. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3882. */
  3883. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3884. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3885. };
  3886. /**
  3887. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3888. */
  3889. Vector4.prototype.divide = function (otherVector) {
  3890. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3891. };
  3892. /**
  3893. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3894. * Returns the current Vector4.
  3895. */
  3896. Vector4.prototype.divideToRef = function (otherVector, result) {
  3897. result.x = this.x / otherVector.x;
  3898. result.y = this.y / otherVector.y;
  3899. result.z = this.z / otherVector.z;
  3900. result.w = this.w / otherVector.w;
  3901. return this;
  3902. };
  3903. /**
  3904. * Divides the current Vector3 coordinates by the passed ones.
  3905. * @returns the updated Vector3.
  3906. */
  3907. Vector4.prototype.divideInPlace = function (otherVector) {
  3908. return this.divideToRef(otherVector, this);
  3909. };
  3910. /**
  3911. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3912. * @param other defines the second operand
  3913. * @returns the current updated Vector4
  3914. */
  3915. Vector4.prototype.minimizeInPlace = function (other) {
  3916. if (other.x < this.x)
  3917. this.x = other.x;
  3918. if (other.y < this.y)
  3919. this.y = other.y;
  3920. if (other.z < this.z)
  3921. this.z = other.z;
  3922. if (other.w < this.w)
  3923. this.w = other.w;
  3924. return this;
  3925. };
  3926. /**
  3927. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  3928. * @param other defines the second operand
  3929. * @returns the current updated Vector4
  3930. */
  3931. Vector4.prototype.maximizeInPlace = function (other) {
  3932. if (other.x > this.x)
  3933. this.x = other.x;
  3934. if (other.y > this.y)
  3935. this.y = other.y;
  3936. if (other.z > this.z)
  3937. this.z = other.z;
  3938. if (other.w > this.w)
  3939. this.w = other.w;
  3940. return this;
  3941. };
  3942. // Properties
  3943. /**
  3944. * Returns the Vector4 length (float).
  3945. */
  3946. Vector4.prototype.length = function () {
  3947. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3948. };
  3949. /**
  3950. * Returns the Vector4 squared length (float).
  3951. */
  3952. Vector4.prototype.lengthSquared = function () {
  3953. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3954. };
  3955. // Methods
  3956. /**
  3957. * Normalizes in place the Vector4.
  3958. * Returns the updated Vector4.
  3959. */
  3960. Vector4.prototype.normalize = function () {
  3961. var len = this.length();
  3962. if (len === 0)
  3963. return this;
  3964. var num = 1.0 / len;
  3965. this.x *= num;
  3966. this.y *= num;
  3967. this.z *= num;
  3968. this.w *= num;
  3969. return this;
  3970. };
  3971. /**
  3972. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3973. */
  3974. Vector4.prototype.toVector3 = function () {
  3975. return new Vector3(this.x, this.y, this.z);
  3976. };
  3977. /**
  3978. * Returns a new Vector4 copied from the current one.
  3979. */
  3980. Vector4.prototype.clone = function () {
  3981. return new Vector4(this.x, this.y, this.z, this.w);
  3982. };
  3983. /**
  3984. * Updates the current Vector4 with the passed one coordinates.
  3985. * Returns the updated Vector4.
  3986. */
  3987. Vector4.prototype.copyFrom = function (source) {
  3988. this.x = source.x;
  3989. this.y = source.y;
  3990. this.z = source.z;
  3991. this.w = source.w;
  3992. return this;
  3993. };
  3994. /**
  3995. * Updates the current Vector4 coordinates with the passed floats.
  3996. * Returns the updated Vector4.
  3997. */
  3998. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3999. this.x = x;
  4000. this.y = y;
  4001. this.z = z;
  4002. this.w = w;
  4003. return this;
  4004. };
  4005. /**
  4006. * Updates the current Vector4 coordinates with the passed floats.
  4007. * Returns the updated Vector4.
  4008. */
  4009. Vector4.prototype.set = function (x, y, z, w) {
  4010. return this.copyFromFloats(x, y, z, w);
  4011. };
  4012. // Statics
  4013. /**
  4014. * Returns a new Vector4 set from the starting index of the passed array.
  4015. */
  4016. Vector4.FromArray = function (array, offset) {
  4017. if (!offset) {
  4018. offset = 0;
  4019. }
  4020. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4021. };
  4022. /**
  4023. * Updates the passed vector "result" from the starting index of the passed array.
  4024. */
  4025. Vector4.FromArrayToRef = function (array, offset, result) {
  4026. result.x = array[offset];
  4027. result.y = array[offset + 1];
  4028. result.z = array[offset + 2];
  4029. result.w = array[offset + 3];
  4030. };
  4031. /**
  4032. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  4033. */
  4034. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4035. Vector4.FromArrayToRef(array, offset, result);
  4036. };
  4037. /**
  4038. * Updates the passed vector "result" coordinates from the passed floats.
  4039. */
  4040. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4041. result.x = x;
  4042. result.y = y;
  4043. result.z = z;
  4044. result.w = w;
  4045. };
  4046. /**
  4047. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4048. */
  4049. Vector4.Zero = function () {
  4050. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4051. };
  4052. /**
  4053. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4054. */
  4055. Vector4.One = function () {
  4056. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4057. };
  4058. /**
  4059. * Returns a new normalized Vector4 from the passed one.
  4060. */
  4061. Vector4.Normalize = function (vector) {
  4062. var result = Vector4.Zero();
  4063. Vector4.NormalizeToRef(vector, result);
  4064. return result;
  4065. };
  4066. /**
  4067. * Updates the passed vector "result" from the normalization of the passed one.
  4068. */
  4069. Vector4.NormalizeToRef = function (vector, result) {
  4070. result.copyFrom(vector);
  4071. result.normalize();
  4072. };
  4073. Vector4.Minimize = function (left, right) {
  4074. var min = left.clone();
  4075. min.minimizeInPlace(right);
  4076. return min;
  4077. };
  4078. Vector4.Maximize = function (left, right) {
  4079. var max = left.clone();
  4080. max.maximizeInPlace(right);
  4081. return max;
  4082. };
  4083. /**
  4084. * Returns the distance (float) between the vectors "value1" and "value2".
  4085. */
  4086. Vector4.Distance = function (value1, value2) {
  4087. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4088. };
  4089. /**
  4090. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4091. */
  4092. Vector4.DistanceSquared = function (value1, value2) {
  4093. var x = value1.x - value2.x;
  4094. var y = value1.y - value2.y;
  4095. var z = value1.z - value2.z;
  4096. var w = value1.w - value2.w;
  4097. return (x * x) + (y * y) + (z * z) + (w * w);
  4098. };
  4099. /**
  4100. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4101. */
  4102. Vector4.Center = function (value1, value2) {
  4103. var center = value1.add(value2);
  4104. center.scaleInPlace(0.5);
  4105. return center;
  4106. };
  4107. /**
  4108. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  4109. * This methods computes transformed normalized direction vectors only.
  4110. */
  4111. Vector4.TransformNormal = function (vector, transformation) {
  4112. var result = Vector4.Zero();
  4113. Vector4.TransformNormalToRef(vector, transformation, result);
  4114. return result;
  4115. };
  4116. /**
  4117. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  4118. * This methods computes transformed normalized direction vectors only.
  4119. */
  4120. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4121. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4122. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4123. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4124. result.x = x;
  4125. result.y = y;
  4126. result.z = z;
  4127. result.w = vector.w;
  4128. };
  4129. /**
  4130. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  4131. * This methods computes transformed normalized direction vectors only.
  4132. */
  4133. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4134. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4135. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4136. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4137. result.w = w;
  4138. };
  4139. return Vector4;
  4140. }());
  4141. BABYLON.Vector4 = Vector4;
  4142. var Size = /** @class */ (function () {
  4143. /**
  4144. * Creates a Size object from the passed width and height (floats).
  4145. */
  4146. function Size(width, height) {
  4147. this.width = width;
  4148. this.height = height;
  4149. }
  4150. // Returns a string with the Size width and height.
  4151. Size.prototype.toString = function () {
  4152. return "{W: " + this.width + ", H: " + this.height + "}";
  4153. };
  4154. /**
  4155. * Returns the string "Size"
  4156. */
  4157. Size.prototype.getClassName = function () {
  4158. return "Size";
  4159. };
  4160. /**
  4161. * Returns the Size hash code.
  4162. */
  4163. Size.prototype.getHashCode = function () {
  4164. var hash = this.width || 0;
  4165. hash = (hash * 397) ^ (this.height || 0);
  4166. return hash;
  4167. };
  4168. /**
  4169. * Updates the current size from the passed one.
  4170. * Returns the updated Size.
  4171. */
  4172. Size.prototype.copyFrom = function (src) {
  4173. this.width = src.width;
  4174. this.height = src.height;
  4175. };
  4176. /**
  4177. * Updates in place the current Size from the passed floats.
  4178. * Returns the updated Size.
  4179. */
  4180. Size.prototype.copyFromFloats = function (width, height) {
  4181. this.width = width;
  4182. this.height = height;
  4183. return this;
  4184. };
  4185. /**
  4186. * Updates in place the current Size from the passed floats.
  4187. * Returns the updated Size.
  4188. */
  4189. Size.prototype.set = function (width, height) {
  4190. return this.copyFromFloats(width, height);
  4191. };
  4192. /**
  4193. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4194. */
  4195. Size.prototype.multiplyByFloats = function (w, h) {
  4196. return new Size(this.width * w, this.height * h);
  4197. };
  4198. /**
  4199. * Returns a new Size copied from the passed one.
  4200. */
  4201. Size.prototype.clone = function () {
  4202. return new Size(this.width, this.height);
  4203. };
  4204. /**
  4205. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4206. */
  4207. Size.prototype.equals = function (other) {
  4208. if (!other) {
  4209. return false;
  4210. }
  4211. return (this.width === other.width) && (this.height === other.height);
  4212. };
  4213. Object.defineProperty(Size.prototype, "surface", {
  4214. /**
  4215. * Returns the surface of the Size : width * height (float).
  4216. */
  4217. get: function () {
  4218. return this.width * this.height;
  4219. },
  4220. enumerable: true,
  4221. configurable: true
  4222. });
  4223. /**
  4224. * Returns a new Size set to (0.0, 0.0)
  4225. */
  4226. Size.Zero = function () {
  4227. return new Size(0.0, 0.0);
  4228. };
  4229. /**
  4230. * Returns a new Size set as the addition result of the current Size and the passed one.
  4231. */
  4232. Size.prototype.add = function (otherSize) {
  4233. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4234. return r;
  4235. };
  4236. /**
  4237. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4238. */
  4239. Size.prototype.subtract = function (otherSize) {
  4240. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4241. return r;
  4242. };
  4243. /**
  4244. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4245. */
  4246. Size.Lerp = function (start, end, amount) {
  4247. var w = start.width + ((end.width - start.width) * amount);
  4248. var h = start.height + ((end.height - start.height) * amount);
  4249. return new Size(w, h);
  4250. };
  4251. return Size;
  4252. }());
  4253. BABYLON.Size = Size;
  4254. var Quaternion = /** @class */ (function () {
  4255. /**
  4256. * Creates a new Quaternion from the passed floats.
  4257. */
  4258. function Quaternion(x, y, z, w) {
  4259. if (x === void 0) { x = 0.0; }
  4260. if (y === void 0) { y = 0.0; }
  4261. if (z === void 0) { z = 0.0; }
  4262. if (w === void 0) { w = 1.0; }
  4263. this.x = x;
  4264. this.y = y;
  4265. this.z = z;
  4266. this.w = w;
  4267. }
  4268. /**
  4269. * Returns a string with the Quaternion coordinates.
  4270. */
  4271. Quaternion.prototype.toString = function () {
  4272. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4273. };
  4274. /**
  4275. * Returns the string "Quaternion".
  4276. */
  4277. Quaternion.prototype.getClassName = function () {
  4278. return "Quaternion";
  4279. };
  4280. /**
  4281. * Returns the Quaternion hash code.
  4282. */
  4283. Quaternion.prototype.getHashCode = function () {
  4284. var hash = this.x || 0;
  4285. hash = (hash * 397) ^ (this.y || 0);
  4286. hash = (hash * 397) ^ (this.z || 0);
  4287. hash = (hash * 397) ^ (this.w || 0);
  4288. return hash;
  4289. };
  4290. /**
  4291. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4292. */
  4293. Quaternion.prototype.asArray = function () {
  4294. return [this.x, this.y, this.z, this.w];
  4295. };
  4296. /**
  4297. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4298. */
  4299. Quaternion.prototype.equals = function (otherQuaternion) {
  4300. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4301. };
  4302. /**
  4303. * Returns a new Quaternion copied from the current one.
  4304. */
  4305. Quaternion.prototype.clone = function () {
  4306. return new Quaternion(this.x, this.y, this.z, this.w);
  4307. };
  4308. /**
  4309. * Updates the current Quaternion from the passed one coordinates.
  4310. * Returns the updated Quaterion.
  4311. */
  4312. Quaternion.prototype.copyFrom = function (other) {
  4313. this.x = other.x;
  4314. this.y = other.y;
  4315. this.z = other.z;
  4316. this.w = other.w;
  4317. return this;
  4318. };
  4319. /**
  4320. * Updates the current Quaternion from the passed float coordinates.
  4321. * Returns the updated Quaterion.
  4322. */
  4323. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4324. this.x = x;
  4325. this.y = y;
  4326. this.z = z;
  4327. this.w = w;
  4328. return this;
  4329. };
  4330. /**
  4331. * Updates the current Quaternion from the passed float coordinates.
  4332. * Returns the updated Quaterion.
  4333. */
  4334. Quaternion.prototype.set = function (x, y, z, w) {
  4335. return this.copyFromFloats(x, y, z, w);
  4336. };
  4337. /**
  4338. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4339. */
  4340. Quaternion.prototype.add = function (other) {
  4341. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4342. };
  4343. /**
  4344. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4345. */
  4346. Quaternion.prototype.subtract = function (other) {
  4347. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4348. };
  4349. /**
  4350. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4351. */
  4352. Quaternion.prototype.scale = function (value) {
  4353. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4354. };
  4355. /**
  4356. * Scale the current Quaternion values by a factor to a given Quaternion
  4357. * @param scale defines the scale factor
  4358. * @param result defines the Quaternion object where to store the result
  4359. * @returns the unmodified current Quaternion
  4360. */
  4361. Quaternion.prototype.scaleToRef = function (scale, result) {
  4362. result.x = this.x * scale;
  4363. result.y = this.y * scale;
  4364. result.z = this.z * scale;
  4365. result.w = this.w * scale;
  4366. return this;
  4367. };
  4368. /**
  4369. * Scale the current Quaternion values by a factor and add the result to a given Quaternion
  4370. * @param scale defines the scale factor
  4371. * @param result defines the Quaternion object where to store the result
  4372. * @returns the unmodified current Quaternion
  4373. */
  4374. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4375. result.x += this.x * scale;
  4376. result.y += this.y * scale;
  4377. result.z += this.z * scale;
  4378. result.w += this.w * scale;
  4379. return this;
  4380. };
  4381. /**
  4382. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4383. */
  4384. Quaternion.prototype.multiply = function (q1) {
  4385. var result = new Quaternion(0, 0, 0, 1.0);
  4386. this.multiplyToRef(q1, result);
  4387. return result;
  4388. };
  4389. /**
  4390. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4391. * Returns the current Quaternion.
  4392. */
  4393. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4394. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4395. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4396. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4397. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4398. result.copyFromFloats(x, y, z, w);
  4399. return this;
  4400. };
  4401. /**
  4402. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4403. * Returns the updated Quaternion.
  4404. */
  4405. Quaternion.prototype.multiplyInPlace = function (q1) {
  4406. this.multiplyToRef(q1, this);
  4407. return this;
  4408. };
  4409. /**
  4410. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4411. * Returns the current Quaternion.
  4412. */
  4413. Quaternion.prototype.conjugateToRef = function (ref) {
  4414. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4415. return this;
  4416. };
  4417. /**
  4418. * Conjugates in place the current Quaternion.
  4419. * Returns the updated Quaternion.
  4420. */
  4421. Quaternion.prototype.conjugateInPlace = function () {
  4422. this.x *= -1;
  4423. this.y *= -1;
  4424. this.z *= -1;
  4425. return this;
  4426. };
  4427. /**
  4428. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4429. */
  4430. Quaternion.prototype.conjugate = function () {
  4431. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4432. return result;
  4433. };
  4434. /**
  4435. * Returns the Quaternion length (float).
  4436. */
  4437. Quaternion.prototype.length = function () {
  4438. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4439. };
  4440. /**
  4441. * Normalize in place the current Quaternion.
  4442. * Returns the updated Quaternion.
  4443. */
  4444. Quaternion.prototype.normalize = function () {
  4445. var length = 1.0 / this.length();
  4446. this.x *= length;
  4447. this.y *= length;
  4448. this.z *= length;
  4449. this.w *= length;
  4450. return this;
  4451. };
  4452. /**
  4453. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion
  4454. * @param order is a reserved parameter and is ignore for now
  4455. * @returns the new Vector3
  4456. */
  4457. Quaternion.prototype.toEulerAngles = function (order) {
  4458. if (order === void 0) { order = "YZX"; }
  4459. var result = Vector3.Zero();
  4460. this.toEulerAnglesToRef(result, order);
  4461. return result;
  4462. };
  4463. /**
  4464. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion
  4465. * @param result defines the vector which will be filled with the Euler angles
  4466. * @param order is a reserved parameter and is ignore for now
  4467. * @returns the current Quaternion
  4468. */
  4469. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4470. if (order === void 0) { order = "YZX"; }
  4471. var qz = this.z;
  4472. var qx = this.x;
  4473. var qy = this.y;
  4474. var qw = this.w;
  4475. var sqw = qw * qw;
  4476. var sqz = qz * qz;
  4477. var sqx = qx * qx;
  4478. var sqy = qy * qy;
  4479. var zAxisY = qy * qz - qx * qw;
  4480. var limit = .4999999;
  4481. if (zAxisY < -limit) {
  4482. result.y = 2 * Math.atan2(qy, qw);
  4483. result.x = Math.PI / 2;
  4484. result.z = 0;
  4485. }
  4486. else if (zAxisY > limit) {
  4487. result.y = 2 * Math.atan2(qy, qw);
  4488. result.x = -Math.PI / 2;
  4489. result.z = 0;
  4490. }
  4491. else {
  4492. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4493. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4494. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4495. }
  4496. return this;
  4497. };
  4498. /**
  4499. * Updates the passed rotation matrix with the current Quaternion values.
  4500. * Returns the current Quaternion.
  4501. */
  4502. Quaternion.prototype.toRotationMatrix = function (result) {
  4503. var xx = this.x * this.x;
  4504. var yy = this.y * this.y;
  4505. var zz = this.z * this.z;
  4506. var xy = this.x * this.y;
  4507. var zw = this.z * this.w;
  4508. var zx = this.z * this.x;
  4509. var yw = this.y * this.w;
  4510. var yz = this.y * this.z;
  4511. var xw = this.x * this.w;
  4512. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4513. result.m[1] = 2.0 * (xy + zw);
  4514. result.m[2] = 2.0 * (zx - yw);
  4515. result.m[3] = 0;
  4516. result.m[4] = 2.0 * (xy - zw);
  4517. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4518. result.m[6] = 2.0 * (yz + xw);
  4519. result.m[7] = 0;
  4520. result.m[8] = 2.0 * (zx + yw);
  4521. result.m[9] = 2.0 * (yz - xw);
  4522. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4523. result.m[11] = 0;
  4524. result.m[12] = 0;
  4525. result.m[13] = 0;
  4526. result.m[14] = 0;
  4527. result.m[15] = 1.0;
  4528. result._markAsUpdated();
  4529. return this;
  4530. };
  4531. /**
  4532. * Updates the current Quaternion from the passed rotation matrix values.
  4533. * Returns the updated Quaternion.
  4534. */
  4535. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4536. Quaternion.FromRotationMatrixToRef(matrix, this);
  4537. return this;
  4538. };
  4539. // Statics
  4540. /**
  4541. * Returns a new Quaternion set from the passed rotation matrix values.
  4542. */
  4543. Quaternion.FromRotationMatrix = function (matrix) {
  4544. var result = new Quaternion();
  4545. Quaternion.FromRotationMatrixToRef(matrix, result);
  4546. return result;
  4547. };
  4548. /**
  4549. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4550. */
  4551. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4552. var data = matrix.m;
  4553. var m11 = data[0], m12 = data[4], m13 = data[8];
  4554. var m21 = data[1], m22 = data[5], m23 = data[9];
  4555. var m31 = data[2], m32 = data[6], m33 = data[10];
  4556. var trace = m11 + m22 + m33;
  4557. var s;
  4558. if (trace > 0) {
  4559. s = 0.5 / Math.sqrt(trace + 1.0);
  4560. result.w = 0.25 / s;
  4561. result.x = (m32 - m23) * s;
  4562. result.y = (m13 - m31) * s;
  4563. result.z = (m21 - m12) * s;
  4564. }
  4565. else if (m11 > m22 && m11 > m33) {
  4566. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4567. result.w = (m32 - m23) / s;
  4568. result.x = 0.25 * s;
  4569. result.y = (m12 + m21) / s;
  4570. result.z = (m13 + m31) / s;
  4571. }
  4572. else if (m22 > m33) {
  4573. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4574. result.w = (m13 - m31) / s;
  4575. result.x = (m12 + m21) / s;
  4576. result.y = 0.25 * s;
  4577. result.z = (m23 + m32) / s;
  4578. }
  4579. else {
  4580. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4581. result.w = (m21 - m12) / s;
  4582. result.x = (m13 + m31) / s;
  4583. result.y = (m23 + m32) / s;
  4584. result.z = 0.25 * s;
  4585. }
  4586. };
  4587. /**
  4588. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4589. */
  4590. Quaternion.Zero = function () {
  4591. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4592. };
  4593. /**
  4594. * Returns a new Quaternion as the inverted current Quaternion.
  4595. */
  4596. Quaternion.Inverse = function (q) {
  4597. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4598. };
  4599. /**
  4600. * Returns the identity Quaternion.
  4601. */
  4602. Quaternion.Identity = function () {
  4603. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4604. };
  4605. Quaternion.IsIdentity = function (quaternion) {
  4606. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4607. };
  4608. /**
  4609. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4610. */
  4611. Quaternion.RotationAxis = function (axis, angle) {
  4612. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4613. };
  4614. /**
  4615. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4616. */
  4617. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4618. var sin = Math.sin(angle / 2);
  4619. axis.normalize();
  4620. result.w = Math.cos(angle / 2);
  4621. result.x = axis.x * sin;
  4622. result.y = axis.y * sin;
  4623. result.z = axis.z * sin;
  4624. return result;
  4625. };
  4626. /**
  4627. * Retuns a new Quaternion set from the starting index of the passed array.
  4628. */
  4629. Quaternion.FromArray = function (array, offset) {
  4630. if (!offset) {
  4631. offset = 0;
  4632. }
  4633. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4634. };
  4635. /**
  4636. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4637. */
  4638. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4639. var q = new Quaternion();
  4640. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4641. return q;
  4642. };
  4643. /**
  4644. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4645. */
  4646. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4647. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4648. var halfRoll = roll * 0.5;
  4649. var halfPitch = pitch * 0.5;
  4650. var halfYaw = yaw * 0.5;
  4651. var sinRoll = Math.sin(halfRoll);
  4652. var cosRoll = Math.cos(halfRoll);
  4653. var sinPitch = Math.sin(halfPitch);
  4654. var cosPitch = Math.cos(halfPitch);
  4655. var sinYaw = Math.sin(halfYaw);
  4656. var cosYaw = Math.cos(halfYaw);
  4657. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4658. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4659. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4660. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4661. };
  4662. /**
  4663. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4664. */
  4665. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4666. var result = new Quaternion();
  4667. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4668. return result;
  4669. };
  4670. /**
  4671. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4672. */
  4673. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4674. // Produces a quaternion from Euler angles in the z-x-z orientation
  4675. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4676. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4677. var halfBeta = beta * 0.5;
  4678. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4679. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4680. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4681. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4682. };
  4683. /**
  4684. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4685. * cf to Vector3.RotationFromAxis() documentation.
  4686. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4687. */
  4688. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4689. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4690. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4691. return quat;
  4692. };
  4693. /**
  4694. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4695. * cf to Vector3.RotationFromAxis() documentation.
  4696. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4697. */
  4698. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4699. var rotMat = MathTmp.Matrix[0];
  4700. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4701. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4702. };
  4703. Quaternion.Slerp = function (left, right, amount) {
  4704. var result = Quaternion.Identity();
  4705. Quaternion.SlerpToRef(left, right, amount, result);
  4706. return result;
  4707. };
  4708. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4709. var num2;
  4710. var num3;
  4711. var num = amount;
  4712. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4713. var flag = false;
  4714. if (num4 < 0) {
  4715. flag = true;
  4716. num4 = -num4;
  4717. }
  4718. if (num4 > 0.999999) {
  4719. num3 = 1 - num;
  4720. num2 = flag ? -num : num;
  4721. }
  4722. else {
  4723. var num5 = Math.acos(num4);
  4724. var num6 = (1.0 / Math.sin(num5));
  4725. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4726. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4727. }
  4728. result.x = (num3 * left.x) + (num2 * right.x);
  4729. result.y = (num3 * left.y) + (num2 * right.y);
  4730. result.z = (num3 * left.z) + (num2 * right.z);
  4731. result.w = (num3 * left.w) + (num2 * right.w);
  4732. };
  4733. /**
  4734. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4735. */
  4736. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4737. var squared = amount * amount;
  4738. var cubed = amount * squared;
  4739. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4740. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4741. var part3 = (cubed - (2.0 * squared)) + amount;
  4742. var part4 = cubed - squared;
  4743. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4744. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4745. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4746. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4747. return new Quaternion(x, y, z, w);
  4748. };
  4749. return Quaternion;
  4750. }());
  4751. BABYLON.Quaternion = Quaternion;
  4752. var Matrix = /** @class */ (function () {
  4753. function Matrix() {
  4754. this._isIdentity = false;
  4755. this._isIdentityDirty = true;
  4756. this.m = new Float32Array(16);
  4757. this._markAsUpdated();
  4758. }
  4759. Matrix.prototype._markAsUpdated = function () {
  4760. this.updateFlag = Matrix._updateFlagSeed++;
  4761. this._isIdentityDirty = true;
  4762. };
  4763. // Properties
  4764. /**
  4765. * Boolean : True is the matrix is the identity matrix
  4766. */
  4767. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4768. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4769. if (this._isIdentityDirty) {
  4770. this._isIdentityDirty = false;
  4771. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4772. this._isIdentity = false;
  4773. }
  4774. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4775. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4776. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4777. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4778. this._isIdentity = false;
  4779. }
  4780. else {
  4781. this._isIdentity = true;
  4782. }
  4783. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4784. this._isIdentity = false;
  4785. }
  4786. }
  4787. return this._isIdentity;
  4788. };
  4789. /**
  4790. * Returns the matrix determinant (float).
  4791. */
  4792. Matrix.prototype.determinant = function () {
  4793. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4794. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4795. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4796. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4797. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4798. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4799. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4800. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4801. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4802. };
  4803. // Methods
  4804. /**
  4805. * Returns the matrix underlying array.
  4806. */
  4807. Matrix.prototype.toArray = function () {
  4808. return this.m;
  4809. };
  4810. /**
  4811. * Returns the matrix underlying array.
  4812. */
  4813. Matrix.prototype.asArray = function () {
  4814. return this.toArray();
  4815. };
  4816. /**
  4817. * Inverts in place the Matrix.
  4818. * Returns the Matrix inverted.
  4819. */
  4820. Matrix.prototype.invert = function () {
  4821. this.invertToRef(this);
  4822. return this;
  4823. };
  4824. /**
  4825. * Sets all the matrix elements to zero.
  4826. * Returns the Matrix.
  4827. */
  4828. Matrix.prototype.reset = function () {
  4829. for (var index = 0; index < 16; index++) {
  4830. this.m[index] = 0.0;
  4831. }
  4832. this._markAsUpdated();
  4833. return this;
  4834. };
  4835. /**
  4836. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4837. */
  4838. Matrix.prototype.add = function (other) {
  4839. var result = new Matrix();
  4840. this.addToRef(other, result);
  4841. return result;
  4842. };
  4843. /**
  4844. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4845. * Returns the Matrix.
  4846. */
  4847. Matrix.prototype.addToRef = function (other, result) {
  4848. for (var index = 0; index < 16; index++) {
  4849. result.m[index] = this.m[index] + other.m[index];
  4850. }
  4851. result._markAsUpdated();
  4852. return this;
  4853. };
  4854. /**
  4855. * Adds in place the passed matrix to the current Matrix.
  4856. * Returns the updated Matrix.
  4857. */
  4858. Matrix.prototype.addToSelf = function (other) {
  4859. for (var index = 0; index < 16; index++) {
  4860. this.m[index] += other.m[index];
  4861. }
  4862. this._markAsUpdated();
  4863. return this;
  4864. };
  4865. /**
  4866. * Sets the passed matrix with the current inverted Matrix.
  4867. * Returns the unmodified current Matrix.
  4868. */
  4869. Matrix.prototype.invertToRef = function (other) {
  4870. var l1 = this.m[0];
  4871. var l2 = this.m[1];
  4872. var l3 = this.m[2];
  4873. var l4 = this.m[3];
  4874. var l5 = this.m[4];
  4875. var l6 = this.m[5];
  4876. var l7 = this.m[6];
  4877. var l8 = this.m[7];
  4878. var l9 = this.m[8];
  4879. var l10 = this.m[9];
  4880. var l11 = this.m[10];
  4881. var l12 = this.m[11];
  4882. var l13 = this.m[12];
  4883. var l14 = this.m[13];
  4884. var l15 = this.m[14];
  4885. var l16 = this.m[15];
  4886. var l17 = (l11 * l16) - (l12 * l15);
  4887. var l18 = (l10 * l16) - (l12 * l14);
  4888. var l19 = (l10 * l15) - (l11 * l14);
  4889. var l20 = (l9 * l16) - (l12 * l13);
  4890. var l21 = (l9 * l15) - (l11 * l13);
  4891. var l22 = (l9 * l14) - (l10 * l13);
  4892. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4893. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4894. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4895. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4896. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4897. var l28 = (l7 * l16) - (l8 * l15);
  4898. var l29 = (l6 * l16) - (l8 * l14);
  4899. var l30 = (l6 * l15) - (l7 * l14);
  4900. var l31 = (l5 * l16) - (l8 * l13);
  4901. var l32 = (l5 * l15) - (l7 * l13);
  4902. var l33 = (l5 * l14) - (l6 * l13);
  4903. var l34 = (l7 * l12) - (l8 * l11);
  4904. var l35 = (l6 * l12) - (l8 * l10);
  4905. var l36 = (l6 * l11) - (l7 * l10);
  4906. var l37 = (l5 * l12) - (l8 * l9);
  4907. var l38 = (l5 * l11) - (l7 * l9);
  4908. var l39 = (l5 * l10) - (l6 * l9);
  4909. other.m[0] = l23 * l27;
  4910. other.m[4] = l24 * l27;
  4911. other.m[8] = l25 * l27;
  4912. other.m[12] = l26 * l27;
  4913. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4914. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4915. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4916. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4917. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4918. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4919. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4920. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4921. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4922. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4923. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4924. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4925. other._markAsUpdated();
  4926. return this;
  4927. };
  4928. /**
  4929. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4930. * Returns the updated Matrix.
  4931. */
  4932. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4933. this.m[12] = x;
  4934. this.m[13] = y;
  4935. this.m[14] = z;
  4936. this._markAsUpdated();
  4937. return this;
  4938. };
  4939. /**
  4940. * Inserts the translation vector in the current Matrix.
  4941. * Returns the updated Matrix.
  4942. */
  4943. Matrix.prototype.setTranslation = function (vector3) {
  4944. this.m[12] = vector3.x;
  4945. this.m[13] = vector3.y;
  4946. this.m[14] = vector3.z;
  4947. this._markAsUpdated();
  4948. return this;
  4949. };
  4950. /**
  4951. * Returns a new Vector3 as the extracted translation from the Matrix.
  4952. */
  4953. Matrix.prototype.getTranslation = function () {
  4954. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4955. };
  4956. /**
  4957. * Fill a Vector3 with the extracted translation from the Matrix.
  4958. */
  4959. Matrix.prototype.getTranslationToRef = function (result) {
  4960. result.x = this.m[12];
  4961. result.y = this.m[13];
  4962. result.z = this.m[14];
  4963. return this;
  4964. };
  4965. /**
  4966. * Remove rotation and scaling part from the Matrix.
  4967. * Returns the updated Matrix.
  4968. */
  4969. Matrix.prototype.removeRotationAndScaling = function () {
  4970. this.setRowFromFloats(0, 1, 0, 0, 0);
  4971. this.setRowFromFloats(1, 0, 1, 0, 0);
  4972. this.setRowFromFloats(2, 0, 0, 1, 0);
  4973. return this;
  4974. };
  4975. /**
  4976. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4977. */
  4978. Matrix.prototype.multiply = function (other) {
  4979. var result = new Matrix();
  4980. this.multiplyToRef(other, result);
  4981. return result;
  4982. };
  4983. /**
  4984. * Updates the current Matrix from the passed one values.
  4985. * Returns the updated Matrix.
  4986. */
  4987. Matrix.prototype.copyFrom = function (other) {
  4988. for (var index = 0; index < 16; index++) {
  4989. this.m[index] = other.m[index];
  4990. }
  4991. this._markAsUpdated();
  4992. return this;
  4993. };
  4994. /**
  4995. * Populates the passed array from the starting index with the Matrix values.
  4996. * Returns the Matrix.
  4997. */
  4998. Matrix.prototype.copyToArray = function (array, offset) {
  4999. if (offset === void 0) { offset = 0; }
  5000. for (var index = 0; index < 16; index++) {
  5001. array[offset + index] = this.m[index];
  5002. }
  5003. return this;
  5004. };
  5005. /**
  5006. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  5007. */
  5008. Matrix.prototype.multiplyToRef = function (other, result) {
  5009. this.multiplyToArray(other, result.m, 0);
  5010. result._markAsUpdated();
  5011. return this;
  5012. };
  5013. /**
  5014. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  5015. */
  5016. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5017. var tm0 = this.m[0];
  5018. var tm1 = this.m[1];
  5019. var tm2 = this.m[2];
  5020. var tm3 = this.m[3];
  5021. var tm4 = this.m[4];
  5022. var tm5 = this.m[5];
  5023. var tm6 = this.m[6];
  5024. var tm7 = this.m[7];
  5025. var tm8 = this.m[8];
  5026. var tm9 = this.m[9];
  5027. var tm10 = this.m[10];
  5028. var tm11 = this.m[11];
  5029. var tm12 = this.m[12];
  5030. var tm13 = this.m[13];
  5031. var tm14 = this.m[14];
  5032. var tm15 = this.m[15];
  5033. var om0 = other.m[0];
  5034. var om1 = other.m[1];
  5035. var om2 = other.m[2];
  5036. var om3 = other.m[3];
  5037. var om4 = other.m[4];
  5038. var om5 = other.m[5];
  5039. var om6 = other.m[6];
  5040. var om7 = other.m[7];
  5041. var om8 = other.m[8];
  5042. var om9 = other.m[9];
  5043. var om10 = other.m[10];
  5044. var om11 = other.m[11];
  5045. var om12 = other.m[12];
  5046. var om13 = other.m[13];
  5047. var om14 = other.m[14];
  5048. var om15 = other.m[15];
  5049. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5050. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5051. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5052. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5053. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5054. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5055. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5056. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5057. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5058. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5059. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5060. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5061. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5062. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5063. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5064. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5065. return this;
  5066. };
  5067. /**
  5068. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  5069. */
  5070. Matrix.prototype.equals = function (value) {
  5071. return value &&
  5072. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5073. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5074. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5075. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5076. };
  5077. /**
  5078. * Returns a new Matrix from the current Matrix.
  5079. */
  5080. Matrix.prototype.clone = function () {
  5081. 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]);
  5082. };
  5083. /**
  5084. * Returns the string "Matrix"
  5085. */
  5086. Matrix.prototype.getClassName = function () {
  5087. return "Matrix";
  5088. };
  5089. /**
  5090. * Returns the Matrix hash code.
  5091. */
  5092. Matrix.prototype.getHashCode = function () {
  5093. var hash = this.m[0] || 0;
  5094. for (var i = 1; i < 16; i++) {
  5095. hash = (hash * 397) ^ (this.m[i] || 0);
  5096. }
  5097. return hash;
  5098. };
  5099. /**
  5100. * Decomposes the current Matrix into :
  5101. * - a scale vector3 passed as a reference to update,
  5102. * - a rotation quaternion passed as a reference to update,
  5103. * - a translation vector3 passed as a reference to update.
  5104. * Returns the true if operation was successful.
  5105. */
  5106. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5107. translation.x = this.m[12];
  5108. translation.y = this.m[13];
  5109. translation.z = this.m[14];
  5110. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5111. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5112. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5113. if (this.determinant() <= 0) {
  5114. scale.y *= -1;
  5115. }
  5116. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5117. rotation.x = 0;
  5118. rotation.y = 0;
  5119. rotation.z = 0;
  5120. rotation.w = 1;
  5121. return false;
  5122. }
  5123. 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]);
  5124. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5125. return true;
  5126. };
  5127. /**
  5128. * Returns the index-th row of the current matrix as a new Vector4.
  5129. */
  5130. Matrix.prototype.getRow = function (index) {
  5131. if (index < 0 || index > 3) {
  5132. return null;
  5133. }
  5134. var i = index * 4;
  5135. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5136. };
  5137. /**
  5138. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5139. * Returns the updated Matrix.
  5140. */
  5141. Matrix.prototype.setRow = function (index, row) {
  5142. if (index < 0 || index > 3) {
  5143. return this;
  5144. }
  5145. var i = index * 4;
  5146. this.m[i + 0] = row.x;
  5147. this.m[i + 1] = row.y;
  5148. this.m[i + 2] = row.z;
  5149. this.m[i + 3] = row.w;
  5150. this._markAsUpdated();
  5151. return this;
  5152. };
  5153. /**
  5154. * Compute the transpose of the matrix.
  5155. * Returns a new Matrix.
  5156. */
  5157. Matrix.prototype.transpose = function () {
  5158. return Matrix.Transpose(this);
  5159. };
  5160. /**
  5161. * Compute the transpose of the matrix.
  5162. * Returns the current matrix.
  5163. */
  5164. Matrix.prototype.transposeToRef = function (result) {
  5165. Matrix.TransposeToRef(this, result);
  5166. return this;
  5167. };
  5168. /**
  5169. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5170. * Returns the updated Matrix.
  5171. */
  5172. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5173. if (index < 0 || index > 3) {
  5174. return this;
  5175. }
  5176. var i = index * 4;
  5177. this.m[i + 0] = x;
  5178. this.m[i + 1] = y;
  5179. this.m[i + 2] = z;
  5180. this.m[i + 3] = w;
  5181. this._markAsUpdated();
  5182. return this;
  5183. };
  5184. /**
  5185. * Compute a new Matrix set with the current Matrix values multiplied by scale (float)
  5186. * @param scale defines the scale factor
  5187. * @returns a new Matrix
  5188. */
  5189. Matrix.prototype.scale = function (scale) {
  5190. var result = new Matrix();
  5191. this.scaleToRef(scale, result);
  5192. return result;
  5193. };
  5194. /**
  5195. * Scale the current Matrix values by a factor to a given result Matrix
  5196. * @param scale defines the scale factor
  5197. * @param result defines the Matrix to store the result
  5198. * @returns the current Matrix
  5199. */
  5200. Matrix.prototype.scaleToRef = function (scale, result) {
  5201. for (var index = 0; index < 16; index++) {
  5202. result.m[index] = this.m[index] * scale;
  5203. }
  5204. result._markAsUpdated();
  5205. return this;
  5206. };
  5207. /**
  5208. * Scale the current Matrix values by a factor and add the result to a given Matrix
  5209. * @param scale defines the scale factor
  5210. * @param result defines the Matrix to store the result
  5211. * @returns the current Matrix
  5212. */
  5213. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5214. for (var index = 0; index < 16; index++) {
  5215. result.m[index] += this.m[index] * scale;
  5216. }
  5217. result._markAsUpdated();
  5218. return this;
  5219. };
  5220. /**
  5221. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5222. * @param ref matrix to store the result
  5223. */
  5224. Matrix.prototype.toNormalMatrix = function (ref) {
  5225. this.invertToRef(ref);
  5226. ref.transpose();
  5227. var m = ref.m;
  5228. 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);
  5229. };
  5230. /**
  5231. * Returns a new Matrix as the extracted rotation matrix from the current one.
  5232. */
  5233. Matrix.prototype.getRotationMatrix = function () {
  5234. var result = Matrix.Identity();
  5235. this.getRotationMatrixToRef(result);
  5236. return result;
  5237. };
  5238. /**
  5239. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  5240. * Returns the current Matrix.
  5241. */
  5242. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5243. var m = this.m;
  5244. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  5245. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  5246. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  5247. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5248. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5249. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5250. 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);
  5251. return this;
  5252. };
  5253. // Statics
  5254. /**
  5255. * Returns a new Matrix set from the starting index of the passed array.
  5256. */
  5257. Matrix.FromArray = function (array, offset) {
  5258. var result = new Matrix();
  5259. if (!offset) {
  5260. offset = 0;
  5261. }
  5262. Matrix.FromArrayToRef(array, offset, result);
  5263. return result;
  5264. };
  5265. /**
  5266. * Sets the passed "result" matrix from the starting index of the passed array.
  5267. */
  5268. Matrix.FromArrayToRef = function (array, offset, result) {
  5269. for (var index = 0; index < 16; index++) {
  5270. result.m[index] = array[index + offset];
  5271. }
  5272. result._markAsUpdated();
  5273. };
  5274. /**
  5275. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  5276. */
  5277. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5278. for (var index = 0; index < 16; index++) {
  5279. result.m[index] = array[index + offset] * scale;
  5280. }
  5281. result._markAsUpdated();
  5282. };
  5283. /**
  5284. * Sets the passed matrix "result" with the 16 passed floats.
  5285. */
  5286. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5287. result.m[0] = initialM11;
  5288. result.m[1] = initialM12;
  5289. result.m[2] = initialM13;
  5290. result.m[3] = initialM14;
  5291. result.m[4] = initialM21;
  5292. result.m[5] = initialM22;
  5293. result.m[6] = initialM23;
  5294. result.m[7] = initialM24;
  5295. result.m[8] = initialM31;
  5296. result.m[9] = initialM32;
  5297. result.m[10] = initialM33;
  5298. result.m[11] = initialM34;
  5299. result.m[12] = initialM41;
  5300. result.m[13] = initialM42;
  5301. result.m[14] = initialM43;
  5302. result.m[15] = initialM44;
  5303. result._markAsUpdated();
  5304. };
  5305. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5306. /**
  5307. * Static identity matrix to be used as readonly matrix
  5308. * Must not be updated.
  5309. */
  5310. get: function () {
  5311. return Matrix._identityReadOnly;
  5312. },
  5313. enumerable: true,
  5314. configurable: true
  5315. });
  5316. /**
  5317. * Returns a new Matrix set from the 16 passed floats.
  5318. */
  5319. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5320. var result = new Matrix();
  5321. result.m[0] = initialM11;
  5322. result.m[1] = initialM12;
  5323. result.m[2] = initialM13;
  5324. result.m[3] = initialM14;
  5325. result.m[4] = initialM21;
  5326. result.m[5] = initialM22;
  5327. result.m[6] = initialM23;
  5328. result.m[7] = initialM24;
  5329. result.m[8] = initialM31;
  5330. result.m[9] = initialM32;
  5331. result.m[10] = initialM33;
  5332. result.m[11] = initialM34;
  5333. result.m[12] = initialM41;
  5334. result.m[13] = initialM42;
  5335. result.m[14] = initialM43;
  5336. result.m[15] = initialM44;
  5337. return result;
  5338. };
  5339. /**
  5340. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5341. */
  5342. Matrix.Compose = function (scale, rotation, translation) {
  5343. var result = Matrix.Identity();
  5344. Matrix.ComposeToRef(scale, rotation, translation, result);
  5345. return result;
  5346. };
  5347. /**
  5348. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5349. */
  5350. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5351. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5352. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5353. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5354. result.setTranslation(translation);
  5355. };
  5356. /**
  5357. * Returns a new indentity Matrix.
  5358. */
  5359. Matrix.Identity = function () {
  5360. 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);
  5361. };
  5362. /**
  5363. * Sets the passed "result" as an identity matrix.
  5364. */
  5365. Matrix.IdentityToRef = function (result) {
  5366. 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);
  5367. };
  5368. /**
  5369. * Returns a new zero Matrix.
  5370. */
  5371. Matrix.Zero = function () {
  5372. 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);
  5373. };
  5374. /**
  5375. * Returns a new rotation matrix for "angle" radians around the X axis.
  5376. */
  5377. Matrix.RotationX = function (angle) {
  5378. var result = new Matrix();
  5379. Matrix.RotationXToRef(angle, result);
  5380. return result;
  5381. };
  5382. /**
  5383. * Returns a new Matrix as the passed inverted one.
  5384. */
  5385. Matrix.Invert = function (source) {
  5386. var result = new Matrix();
  5387. source.invertToRef(result);
  5388. return result;
  5389. };
  5390. /**
  5391. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5392. */
  5393. Matrix.RotationXToRef = function (angle, result) {
  5394. var s = Math.sin(angle);
  5395. var c = Math.cos(angle);
  5396. result.m[0] = 1.0;
  5397. result.m[15] = 1.0;
  5398. result.m[5] = c;
  5399. result.m[10] = c;
  5400. result.m[9] = -s;
  5401. result.m[6] = s;
  5402. result.m[1] = 0.0;
  5403. result.m[2] = 0.0;
  5404. result.m[3] = 0.0;
  5405. result.m[4] = 0.0;
  5406. result.m[7] = 0.0;
  5407. result.m[8] = 0.0;
  5408. result.m[11] = 0.0;
  5409. result.m[12] = 0.0;
  5410. result.m[13] = 0.0;
  5411. result.m[14] = 0.0;
  5412. result._markAsUpdated();
  5413. };
  5414. /**
  5415. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5416. */
  5417. Matrix.RotationY = function (angle) {
  5418. var result = new Matrix();
  5419. Matrix.RotationYToRef(angle, result);
  5420. return result;
  5421. };
  5422. /**
  5423. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5424. */
  5425. Matrix.RotationYToRef = function (angle, result) {
  5426. var s = Math.sin(angle);
  5427. var c = Math.cos(angle);
  5428. result.m[5] = 1.0;
  5429. result.m[15] = 1.0;
  5430. result.m[0] = c;
  5431. result.m[2] = -s;
  5432. result.m[8] = s;
  5433. result.m[10] = c;
  5434. result.m[1] = 0.0;
  5435. result.m[3] = 0.0;
  5436. result.m[4] = 0.0;
  5437. result.m[6] = 0.0;
  5438. result.m[7] = 0.0;
  5439. result.m[9] = 0.0;
  5440. result.m[11] = 0.0;
  5441. result.m[12] = 0.0;
  5442. result.m[13] = 0.0;
  5443. result.m[14] = 0.0;
  5444. result._markAsUpdated();
  5445. };
  5446. /**
  5447. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5448. */
  5449. Matrix.RotationZ = function (angle) {
  5450. var result = new Matrix();
  5451. Matrix.RotationZToRef(angle, result);
  5452. return result;
  5453. };
  5454. /**
  5455. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5456. */
  5457. Matrix.RotationZToRef = function (angle, result) {
  5458. var s = Math.sin(angle);
  5459. var c = Math.cos(angle);
  5460. result.m[10] = 1.0;
  5461. result.m[15] = 1.0;
  5462. result.m[0] = c;
  5463. result.m[1] = s;
  5464. result.m[4] = -s;
  5465. result.m[5] = c;
  5466. result.m[2] = 0.0;
  5467. result.m[3] = 0.0;
  5468. result.m[6] = 0.0;
  5469. result.m[7] = 0.0;
  5470. result.m[8] = 0.0;
  5471. result.m[9] = 0.0;
  5472. result.m[11] = 0.0;
  5473. result.m[12] = 0.0;
  5474. result.m[13] = 0.0;
  5475. result.m[14] = 0.0;
  5476. result._markAsUpdated();
  5477. };
  5478. /**
  5479. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5480. */
  5481. Matrix.RotationAxis = function (axis, angle) {
  5482. var result = Matrix.Zero();
  5483. Matrix.RotationAxisToRef(axis, angle, result);
  5484. return result;
  5485. };
  5486. /**
  5487. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5488. */
  5489. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5490. var s = Math.sin(-angle);
  5491. var c = Math.cos(-angle);
  5492. var c1 = 1 - c;
  5493. axis.normalize();
  5494. result.m[0] = (axis.x * axis.x) * c1 + c;
  5495. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5496. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5497. result.m[3] = 0.0;
  5498. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5499. result.m[5] = (axis.y * axis.y) * c1 + c;
  5500. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5501. result.m[7] = 0.0;
  5502. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5503. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5504. result.m[10] = (axis.z * axis.z) * c1 + c;
  5505. result.m[11] = 0.0;
  5506. result.m[15] = 1.0;
  5507. result._markAsUpdated();
  5508. };
  5509. /**
  5510. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5511. */
  5512. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5513. var result = new Matrix();
  5514. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5515. return result;
  5516. };
  5517. /**
  5518. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5519. */
  5520. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5521. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5522. this._tempQuaternion.toRotationMatrix(result);
  5523. };
  5524. /**
  5525. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5526. */
  5527. Matrix.Scaling = function (x, y, z) {
  5528. var result = Matrix.Zero();
  5529. Matrix.ScalingToRef(x, y, z, result);
  5530. return result;
  5531. };
  5532. /**
  5533. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5534. */
  5535. Matrix.ScalingToRef = function (x, y, z, result) {
  5536. result.m[0] = x;
  5537. result.m[1] = 0.0;
  5538. result.m[2] = 0.0;
  5539. result.m[3] = 0.0;
  5540. result.m[4] = 0.0;
  5541. result.m[5] = y;
  5542. result.m[6] = 0.0;
  5543. result.m[7] = 0.0;
  5544. result.m[8] = 0.0;
  5545. result.m[9] = 0.0;
  5546. result.m[10] = z;
  5547. result.m[11] = 0.0;
  5548. result.m[12] = 0.0;
  5549. result.m[13] = 0.0;
  5550. result.m[14] = 0.0;
  5551. result.m[15] = 1.0;
  5552. result._markAsUpdated();
  5553. };
  5554. /**
  5555. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5556. */
  5557. Matrix.Translation = function (x, y, z) {
  5558. var result = Matrix.Identity();
  5559. Matrix.TranslationToRef(x, y, z, result);
  5560. return result;
  5561. };
  5562. /**
  5563. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5564. */
  5565. Matrix.TranslationToRef = function (x, y, z, result) {
  5566. 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);
  5567. };
  5568. /**
  5569. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5570. * @param startValue defines the start value
  5571. * @param endValue defines the end value
  5572. * @param gradient defines the gradient factor
  5573. * @returns the new matrix
  5574. */
  5575. Matrix.Lerp = function (startValue, endValue, gradient) {
  5576. var result = Matrix.Zero();
  5577. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5578. return result;
  5579. };
  5580. /**
  5581. * Set the passed matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5582. * @param startValue defines the start value
  5583. * @param endValue defines the end value
  5584. * @param gradient defines the gradient factor
  5585. * @param result defines the Matrix object where to store data
  5586. */
  5587. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5588. for (var index = 0; index < 16; index++) {
  5589. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5590. }
  5591. result._markAsUpdated();
  5592. };
  5593. /**
  5594. * Returns a new Matrix whose values are computed by :
  5595. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5596. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5597. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5598. */
  5599. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5600. var startScale = new Vector3(0, 0, 0);
  5601. var startRotation = new Quaternion();
  5602. var startTranslation = new Vector3(0, 0, 0);
  5603. startValue.decompose(startScale, startRotation, startTranslation);
  5604. var endScale = new Vector3(0, 0, 0);
  5605. var endRotation = new Quaternion();
  5606. var endTranslation = new Vector3(0, 0, 0);
  5607. endValue.decompose(endScale, endRotation, endTranslation);
  5608. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5609. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5610. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5611. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5612. };
  5613. /**
  5614. * 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".
  5615. * This methods works for a Left-Handed system.
  5616. */
  5617. Matrix.LookAtLH = function (eye, target, up) {
  5618. var result = Matrix.Zero();
  5619. Matrix.LookAtLHToRef(eye, target, up, result);
  5620. return result;
  5621. };
  5622. /**
  5623. * 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".
  5624. * This methods works for a Left-Handed system.
  5625. */
  5626. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5627. // Z axis
  5628. target.subtractToRef(eye, this._zAxis);
  5629. this._zAxis.normalize();
  5630. // X axis
  5631. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5632. if (this._xAxis.lengthSquared() === 0) {
  5633. this._xAxis.x = 1.0;
  5634. }
  5635. else {
  5636. this._xAxis.normalize();
  5637. }
  5638. // Y axis
  5639. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5640. this._yAxis.normalize();
  5641. // Eye angles
  5642. var ex = -Vector3.Dot(this._xAxis, eye);
  5643. var ey = -Vector3.Dot(this._yAxis, eye);
  5644. var ez = -Vector3.Dot(this._zAxis, eye);
  5645. 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);
  5646. };
  5647. /**
  5648. * 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".
  5649. * This methods works for a Right-Handed system.
  5650. */
  5651. Matrix.LookAtRH = function (eye, target, up) {
  5652. var result = Matrix.Zero();
  5653. Matrix.LookAtRHToRef(eye, target, up, result);
  5654. return result;
  5655. };
  5656. /**
  5657. * 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".
  5658. * This methods works for a Left-Handed system.
  5659. */
  5660. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5661. // Z axis
  5662. eye.subtractToRef(target, this._zAxis);
  5663. this._zAxis.normalize();
  5664. // X axis
  5665. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5666. if (this._xAxis.lengthSquared() === 0) {
  5667. this._xAxis.x = 1.0;
  5668. }
  5669. else {
  5670. this._xAxis.normalize();
  5671. }
  5672. // Y axis
  5673. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5674. this._yAxis.normalize();
  5675. // Eye angles
  5676. var ex = -Vector3.Dot(this._xAxis, eye);
  5677. var ey = -Vector3.Dot(this._yAxis, eye);
  5678. var ez = -Vector3.Dot(this._zAxis, eye);
  5679. 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);
  5680. };
  5681. /**
  5682. * 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.
  5683. */
  5684. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5685. var matrix = Matrix.Zero();
  5686. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5687. return matrix;
  5688. };
  5689. /**
  5690. * 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.
  5691. */
  5692. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5693. var n = znear;
  5694. var f = zfar;
  5695. var a = 2.0 / width;
  5696. var b = 2.0 / height;
  5697. var c = 2.0 / (f - n);
  5698. var d = -(f + n) / (f - n);
  5699. 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);
  5700. };
  5701. /**
  5702. * 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.
  5703. */
  5704. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5705. var matrix = Matrix.Zero();
  5706. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5707. return matrix;
  5708. };
  5709. /**
  5710. * 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.
  5711. */
  5712. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5713. var n = znear;
  5714. var f = zfar;
  5715. var a = 2.0 / (right - left);
  5716. var b = 2.0 / (top - bottom);
  5717. var c = 2.0 / (f - n);
  5718. var d = -(f + n) / (f - n);
  5719. var i0 = (left + right) / (left - right);
  5720. var i1 = (top + bottom) / (bottom - top);
  5721. 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);
  5722. };
  5723. /**
  5724. * 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.
  5725. */
  5726. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5727. var matrix = Matrix.Zero();
  5728. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5729. return matrix;
  5730. };
  5731. /**
  5732. * 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.
  5733. */
  5734. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5735. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5736. result.m[10] *= -1.0;
  5737. };
  5738. /**
  5739. * 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.
  5740. */
  5741. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5742. var matrix = Matrix.Zero();
  5743. var n = znear;
  5744. var f = zfar;
  5745. var a = 2.0 * n / width;
  5746. var b = 2.0 * n / height;
  5747. var c = (f + n) / (f - n);
  5748. var d = -2.0 * f * n / (f - n);
  5749. 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);
  5750. return matrix;
  5751. };
  5752. /**
  5753. * 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.
  5754. */
  5755. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5756. var matrix = Matrix.Zero();
  5757. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5758. return matrix;
  5759. };
  5760. /**
  5761. * 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.
  5762. */
  5763. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5764. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5765. var n = znear;
  5766. var f = zfar;
  5767. var t = 1.0 / (Math.tan(fov * 0.5));
  5768. var a = isVerticalFovFixed ? (t / aspect) : t;
  5769. var b = isVerticalFovFixed ? t : (t * aspect);
  5770. var c = (f + n) / (f - n);
  5771. var d = -2.0 * f * n / (f - n);
  5772. 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);
  5773. };
  5774. /**
  5775. * 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.
  5776. */
  5777. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5778. var matrix = Matrix.Zero();
  5779. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5780. return matrix;
  5781. };
  5782. /**
  5783. * 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.
  5784. */
  5785. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5786. //alternatively this could be expressed as:
  5787. // m = PerspectiveFovLHToRef
  5788. // m[10] *= -1.0;
  5789. // m[11] *= -1.0;
  5790. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5791. var n = znear;
  5792. var f = zfar;
  5793. var t = 1.0 / (Math.tan(fov * 0.5));
  5794. var a = isVerticalFovFixed ? (t / aspect) : t;
  5795. var b = isVerticalFovFixed ? t : (t * aspect);
  5796. var c = -(f + n) / (f - n);
  5797. var d = -2 * f * n / (f - n);
  5798. 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);
  5799. };
  5800. /**
  5801. * 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.
  5802. */
  5803. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5804. if (rightHanded === void 0) { rightHanded = false; }
  5805. var rightHandedFactor = rightHanded ? -1 : 1;
  5806. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5807. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5808. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5809. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5810. var xScale = 2.0 / (leftTan + rightTan);
  5811. var yScale = 2.0 / (upTan + downTan);
  5812. result.m[0] = xScale;
  5813. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5814. result.m[5] = yScale;
  5815. result.m[6] = result.m[7] = 0.0;
  5816. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5817. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5818. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5819. result.m[10] = -zfar / (znear - zfar);
  5820. result.m[11] = 1.0 * rightHandedFactor;
  5821. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5822. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5823. // result.m[14] = (znear * zfar) / (znear - zfar);
  5824. result._markAsUpdated();
  5825. };
  5826. /**
  5827. * Returns the final transformation matrix : world * view * projection * viewport
  5828. */
  5829. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5830. var cw = viewport.width;
  5831. var ch = viewport.height;
  5832. var cx = viewport.x;
  5833. var cy = viewport.y;
  5834. 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);
  5835. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5836. };
  5837. /**
  5838. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5839. */
  5840. Matrix.GetAsMatrix2x2 = function (matrix) {
  5841. return new Float32Array([
  5842. matrix.m[0], matrix.m[1],
  5843. matrix.m[4], matrix.m[5]
  5844. ]);
  5845. };
  5846. /**
  5847. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5848. */
  5849. Matrix.GetAsMatrix3x3 = function (matrix) {
  5850. return new Float32Array([
  5851. matrix.m[0], matrix.m[1], matrix.m[2],
  5852. matrix.m[4], matrix.m[5], matrix.m[6],
  5853. matrix.m[8], matrix.m[9], matrix.m[10]
  5854. ]);
  5855. };
  5856. /**
  5857. * Compute the transpose of the passed Matrix.
  5858. * Returns a new Matrix.
  5859. */
  5860. Matrix.Transpose = function (matrix) {
  5861. var result = new Matrix();
  5862. Matrix.TransposeToRef(matrix, result);
  5863. return result;
  5864. };
  5865. /**
  5866. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5867. */
  5868. Matrix.TransposeToRef = function (matrix, result) {
  5869. result.m[0] = matrix.m[0];
  5870. result.m[1] = matrix.m[4];
  5871. result.m[2] = matrix.m[8];
  5872. result.m[3] = matrix.m[12];
  5873. result.m[4] = matrix.m[1];
  5874. result.m[5] = matrix.m[5];
  5875. result.m[6] = matrix.m[9];
  5876. result.m[7] = matrix.m[13];
  5877. result.m[8] = matrix.m[2];
  5878. result.m[9] = matrix.m[6];
  5879. result.m[10] = matrix.m[10];
  5880. result.m[11] = matrix.m[14];
  5881. result.m[12] = matrix.m[3];
  5882. result.m[13] = matrix.m[7];
  5883. result.m[14] = matrix.m[11];
  5884. result.m[15] = matrix.m[15];
  5885. };
  5886. /**
  5887. * Returns a new Matrix as the reflection matrix across the passed plane.
  5888. */
  5889. Matrix.Reflection = function (plane) {
  5890. var matrix = new Matrix();
  5891. Matrix.ReflectionToRef(plane, matrix);
  5892. return matrix;
  5893. };
  5894. /**
  5895. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5896. */
  5897. Matrix.ReflectionToRef = function (plane, result) {
  5898. plane.normalize();
  5899. var x = plane.normal.x;
  5900. var y = plane.normal.y;
  5901. var z = plane.normal.z;
  5902. var temp = -2 * x;
  5903. var temp2 = -2 * y;
  5904. var temp3 = -2 * z;
  5905. result.m[0] = (temp * x) + 1;
  5906. result.m[1] = temp2 * x;
  5907. result.m[2] = temp3 * x;
  5908. result.m[3] = 0.0;
  5909. result.m[4] = temp * y;
  5910. result.m[5] = (temp2 * y) + 1;
  5911. result.m[6] = temp3 * y;
  5912. result.m[7] = 0.0;
  5913. result.m[8] = temp * z;
  5914. result.m[9] = temp2 * z;
  5915. result.m[10] = (temp3 * z) + 1;
  5916. result.m[11] = 0.0;
  5917. result.m[12] = temp * plane.d;
  5918. result.m[13] = temp2 * plane.d;
  5919. result.m[14] = temp3 * plane.d;
  5920. result.m[15] = 1.0;
  5921. result._markAsUpdated();
  5922. };
  5923. /**
  5924. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5925. */
  5926. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5927. result.m[0] = xaxis.x;
  5928. result.m[1] = xaxis.y;
  5929. result.m[2] = xaxis.z;
  5930. result.m[3] = 0.0;
  5931. result.m[4] = yaxis.x;
  5932. result.m[5] = yaxis.y;
  5933. result.m[6] = yaxis.z;
  5934. result.m[7] = 0.0;
  5935. result.m[8] = zaxis.x;
  5936. result.m[9] = zaxis.y;
  5937. result.m[10] = zaxis.z;
  5938. result.m[11] = 0.0;
  5939. result.m[12] = 0.0;
  5940. result.m[13] = 0.0;
  5941. result.m[14] = 0.0;
  5942. result.m[15] = 1.0;
  5943. result._markAsUpdated();
  5944. };
  5945. /**
  5946. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5947. */
  5948. Matrix.FromQuaternionToRef = function (quat, result) {
  5949. var xx = quat.x * quat.x;
  5950. var yy = quat.y * quat.y;
  5951. var zz = quat.z * quat.z;
  5952. var xy = quat.x * quat.y;
  5953. var zw = quat.z * quat.w;
  5954. var zx = quat.z * quat.x;
  5955. var yw = quat.y * quat.w;
  5956. var yz = quat.y * quat.z;
  5957. var xw = quat.x * quat.w;
  5958. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5959. result.m[1] = 2.0 * (xy + zw);
  5960. result.m[2] = 2.0 * (zx - yw);
  5961. result.m[3] = 0.0;
  5962. result.m[4] = 2.0 * (xy - zw);
  5963. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5964. result.m[6] = 2.0 * (yz + xw);
  5965. result.m[7] = 0.0;
  5966. result.m[8] = 2.0 * (zx + yw);
  5967. result.m[9] = 2.0 * (yz - xw);
  5968. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5969. result.m[11] = 0.0;
  5970. result.m[12] = 0.0;
  5971. result.m[13] = 0.0;
  5972. result.m[14] = 0.0;
  5973. result.m[15] = 1.0;
  5974. result._markAsUpdated();
  5975. };
  5976. Matrix._tempQuaternion = new Quaternion();
  5977. Matrix._xAxis = Vector3.Zero();
  5978. Matrix._yAxis = Vector3.Zero();
  5979. Matrix._zAxis = Vector3.Zero();
  5980. Matrix._updateFlagSeed = 0;
  5981. Matrix._identityReadOnly = Matrix.Identity();
  5982. return Matrix;
  5983. }());
  5984. BABYLON.Matrix = Matrix;
  5985. var Plane = /** @class */ (function () {
  5986. /**
  5987. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  5988. */
  5989. function Plane(a, b, c, d) {
  5990. this.normal = new Vector3(a, b, c);
  5991. this.d = d;
  5992. }
  5993. /**
  5994. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  5995. */
  5996. Plane.prototype.asArray = function () {
  5997. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  5998. };
  5999. // Methods
  6000. /**
  6001. * Returns a new plane copied from the current Plane.
  6002. */
  6003. Plane.prototype.clone = function () {
  6004. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6005. };
  6006. /**
  6007. * Returns the string "Plane".
  6008. */
  6009. Plane.prototype.getClassName = function () {
  6010. return "Plane";
  6011. };
  6012. /**
  6013. * Returns the Plane hash code.
  6014. */
  6015. Plane.prototype.getHashCode = function () {
  6016. var hash = this.normal.getHashCode();
  6017. hash = (hash * 397) ^ (this.d || 0);
  6018. return hash;
  6019. };
  6020. /**
  6021. * Normalize the current Plane in place.
  6022. * Returns the updated Plane.
  6023. */
  6024. Plane.prototype.normalize = function () {
  6025. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6026. var magnitude = 0.0;
  6027. if (norm !== 0) {
  6028. magnitude = 1.0 / norm;
  6029. }
  6030. this.normal.x *= magnitude;
  6031. this.normal.y *= magnitude;
  6032. this.normal.z *= magnitude;
  6033. this.d *= magnitude;
  6034. return this;
  6035. };
  6036. /**
  6037. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  6038. */
  6039. Plane.prototype.transform = function (transformation) {
  6040. var transposedMatrix = Matrix.Transpose(transformation);
  6041. var x = this.normal.x;
  6042. var y = this.normal.y;
  6043. var z = this.normal.z;
  6044. var d = this.d;
  6045. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6046. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6047. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6048. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6049. return new Plane(normalX, normalY, normalZ, finalD);
  6050. };
  6051. /**
  6052. * Returns the dot product (float) of the point coordinates and the plane normal.
  6053. */
  6054. Plane.prototype.dotCoordinate = function (point) {
  6055. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6056. };
  6057. /**
  6058. * Updates the current Plane from the plane defined by the three passed points.
  6059. * Returns the updated Plane.
  6060. */
  6061. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6062. var x1 = point2.x - point1.x;
  6063. var y1 = point2.y - point1.y;
  6064. var z1 = point2.z - point1.z;
  6065. var x2 = point3.x - point1.x;
  6066. var y2 = point3.y - point1.y;
  6067. var z2 = point3.z - point1.z;
  6068. var yz = (y1 * z2) - (z1 * y2);
  6069. var xz = (z1 * x2) - (x1 * z2);
  6070. var xy = (x1 * y2) - (y1 * x2);
  6071. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6072. var invPyth;
  6073. if (pyth !== 0) {
  6074. invPyth = 1.0 / pyth;
  6075. }
  6076. else {
  6077. invPyth = 0.0;
  6078. }
  6079. this.normal.x = yz * invPyth;
  6080. this.normal.y = xz * invPyth;
  6081. this.normal.z = xy * invPyth;
  6082. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6083. return this;
  6084. };
  6085. /**
  6086. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6087. */
  6088. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6089. var dot = Vector3.Dot(this.normal, direction);
  6090. return (dot <= epsilon);
  6091. };
  6092. /**
  6093. * Returns the signed distance (float) from the passed point to the Plane.
  6094. */
  6095. Plane.prototype.signedDistanceTo = function (point) {
  6096. return Vector3.Dot(point, this.normal) + this.d;
  6097. };
  6098. // Statics
  6099. /**
  6100. * Returns a new Plane from the passed array.
  6101. */
  6102. Plane.FromArray = function (array) {
  6103. return new Plane(array[0], array[1], array[2], array[3]);
  6104. };
  6105. /**
  6106. * Returns a new Plane defined by the three passed points.
  6107. */
  6108. Plane.FromPoints = function (point1, point2, point3) {
  6109. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6110. result.copyFromPoints(point1, point2, point3);
  6111. return result;
  6112. };
  6113. /**
  6114. * Returns a new Plane the normal vector to this plane at the passed origin point.
  6115. * Note : the vector "normal" is updated because normalized.
  6116. */
  6117. Plane.FromPositionAndNormal = function (origin, normal) {
  6118. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6119. normal.normalize();
  6120. result.normal = normal;
  6121. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6122. return result;
  6123. };
  6124. /**
  6125. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  6126. */
  6127. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6128. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6129. return Vector3.Dot(point, normal) + d;
  6130. };
  6131. return Plane;
  6132. }());
  6133. BABYLON.Plane = Plane;
  6134. var Viewport = /** @class */ (function () {
  6135. /**
  6136. * Creates a Viewport object located at (x, y) and sized (width, height).
  6137. */
  6138. function Viewport(x, y, width, height) {
  6139. this.x = x;
  6140. this.y = y;
  6141. this.width = width;
  6142. this.height = height;
  6143. }
  6144. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6145. if (renderWidthOrEngine.getRenderWidth) {
  6146. var engine = renderWidthOrEngine;
  6147. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6148. }
  6149. var renderWidth = renderWidthOrEngine;
  6150. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6151. };
  6152. /**
  6153. * Returns a new Viewport copied from the current one.
  6154. */
  6155. Viewport.prototype.clone = function () {
  6156. return new Viewport(this.x, this.y, this.width, this.height);
  6157. };
  6158. return Viewport;
  6159. }());
  6160. BABYLON.Viewport = Viewport;
  6161. var Frustum = /** @class */ (function () {
  6162. function Frustum() {
  6163. }
  6164. /**
  6165. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  6166. */
  6167. Frustum.GetPlanes = function (transform) {
  6168. var frustumPlanes = [];
  6169. for (var index = 0; index < 6; index++) {
  6170. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6171. }
  6172. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6173. return frustumPlanes;
  6174. };
  6175. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6176. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6177. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6178. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6179. frustumPlane.d = transform.m[15] + transform.m[14];
  6180. frustumPlane.normalize();
  6181. };
  6182. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6183. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6184. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6185. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6186. frustumPlane.d = transform.m[15] - transform.m[14];
  6187. frustumPlane.normalize();
  6188. };
  6189. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6190. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6191. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6192. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6193. frustumPlane.d = transform.m[15] + transform.m[12];
  6194. frustumPlane.normalize();
  6195. };
  6196. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6197. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6198. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6199. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6200. frustumPlane.d = transform.m[15] - transform.m[12];
  6201. frustumPlane.normalize();
  6202. };
  6203. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6204. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6205. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6206. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6207. frustumPlane.d = transform.m[15] - transform.m[13];
  6208. frustumPlane.normalize();
  6209. };
  6210. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6211. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6212. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6213. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6214. frustumPlane.d = transform.m[15] + transform.m[13];
  6215. frustumPlane.normalize();
  6216. };
  6217. /**
  6218. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  6219. */
  6220. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6221. // Near
  6222. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6223. // Far
  6224. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6225. // Left
  6226. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6227. // Right
  6228. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6229. // Top
  6230. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6231. // Bottom
  6232. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6233. };
  6234. return Frustum;
  6235. }());
  6236. BABYLON.Frustum = Frustum;
  6237. var Space;
  6238. (function (Space) {
  6239. Space[Space["LOCAL"] = 0] = "LOCAL";
  6240. Space[Space["WORLD"] = 1] = "WORLD";
  6241. Space[Space["BONE"] = 2] = "BONE";
  6242. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6243. var Axis = /** @class */ (function () {
  6244. function Axis() {
  6245. }
  6246. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6247. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6248. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6249. return Axis;
  6250. }());
  6251. BABYLON.Axis = Axis;
  6252. ;
  6253. var BezierCurve = /** @class */ (function () {
  6254. function BezierCurve() {
  6255. }
  6256. /**
  6257. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6258. */
  6259. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6260. // Extract X (which is equal to time here)
  6261. var f0 = 1 - 3 * x2 + 3 * x1;
  6262. var f1 = 3 * x2 - 6 * x1;
  6263. var f2 = 3 * x1;
  6264. var refinedT = t;
  6265. for (var i = 0; i < 5; i++) {
  6266. var refinedT2 = refinedT * refinedT;
  6267. var refinedT3 = refinedT2 * refinedT;
  6268. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6269. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6270. refinedT -= (x - t) * slope;
  6271. refinedT = Math.min(1, Math.max(0, refinedT));
  6272. }
  6273. // Resolve cubic bezier for the given x
  6274. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6275. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6276. Math.pow(refinedT, 3);
  6277. };
  6278. return BezierCurve;
  6279. }());
  6280. BABYLON.BezierCurve = BezierCurve;
  6281. var Orientation;
  6282. (function (Orientation) {
  6283. Orientation[Orientation["CW"] = 0] = "CW";
  6284. Orientation[Orientation["CCW"] = 1] = "CCW";
  6285. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6286. var Angle = /** @class */ (function () {
  6287. /**
  6288. * Creates an Angle object of "radians" radians (float).
  6289. */
  6290. function Angle(radians) {
  6291. var _this = this;
  6292. /**
  6293. * Returns the Angle value in degrees (float).
  6294. */
  6295. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6296. /**
  6297. * Returns the Angle value in radians (float).
  6298. */
  6299. this.radians = function () { return _this._radians; };
  6300. this._radians = radians;
  6301. if (this._radians < 0.0)
  6302. this._radians += (2.0 * Math.PI);
  6303. }
  6304. /**
  6305. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6306. */
  6307. Angle.BetweenTwoPoints = function (a, b) {
  6308. var delta = b.subtract(a);
  6309. var theta = Math.atan2(delta.y, delta.x);
  6310. return new Angle(theta);
  6311. };
  6312. /**
  6313. * Returns a new Angle object from the passed float in radians.
  6314. */
  6315. Angle.FromRadians = function (radians) {
  6316. return new Angle(radians);
  6317. };
  6318. /**
  6319. * Returns a new Angle object from the passed float in degrees.
  6320. */
  6321. Angle.FromDegrees = function (degrees) {
  6322. return new Angle(degrees * Math.PI / 180.0);
  6323. };
  6324. return Angle;
  6325. }());
  6326. BABYLON.Angle = Angle;
  6327. var Arc2 = /** @class */ (function () {
  6328. /**
  6329. * Creates an Arc object from the three passed points : start, middle and end.
  6330. */
  6331. function Arc2(startPoint, midPoint, endPoint) {
  6332. this.startPoint = startPoint;
  6333. this.midPoint = midPoint;
  6334. this.endPoint = endPoint;
  6335. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6336. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6337. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6338. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6339. 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);
  6340. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6341. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6342. var a1 = this.startAngle.degrees();
  6343. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6344. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6345. // angles correction
  6346. if (a2 - a1 > +180.0)
  6347. a2 -= 360.0;
  6348. if (a2 - a1 < -180.0)
  6349. a2 += 360.0;
  6350. if (a3 - a2 > +180.0)
  6351. a3 -= 360.0;
  6352. if (a3 - a2 < -180.0)
  6353. a3 += 360.0;
  6354. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6355. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6356. }
  6357. return Arc2;
  6358. }());
  6359. BABYLON.Arc2 = Arc2;
  6360. var Path2 = /** @class */ (function () {
  6361. /**
  6362. * Creates a Path2 object from the starting 2D coordinates x and y.
  6363. */
  6364. function Path2(x, y) {
  6365. this._points = new Array();
  6366. this._length = 0.0;
  6367. this.closed = false;
  6368. this._points.push(new Vector2(x, y));
  6369. }
  6370. /**
  6371. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6372. * Returns the updated Path2.
  6373. */
  6374. Path2.prototype.addLineTo = function (x, y) {
  6375. if (this.closed) {
  6376. return this;
  6377. }
  6378. var newPoint = new Vector2(x, y);
  6379. var previousPoint = this._points[this._points.length - 1];
  6380. this._points.push(newPoint);
  6381. this._length += newPoint.subtract(previousPoint).length();
  6382. return this;
  6383. };
  6384. /**
  6385. * 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.
  6386. * Returns the updated Path2.
  6387. */
  6388. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6389. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6390. if (this.closed) {
  6391. return this;
  6392. }
  6393. var startPoint = this._points[this._points.length - 1];
  6394. var midPoint = new Vector2(midX, midY);
  6395. var endPoint = new Vector2(endX, endY);
  6396. var arc = new Arc2(startPoint, midPoint, endPoint);
  6397. var increment = arc.angle.radians() / numberOfSegments;
  6398. if (arc.orientation === Orientation.CW)
  6399. increment *= -1;
  6400. var currentAngle = arc.startAngle.radians() + increment;
  6401. for (var i = 0; i < numberOfSegments; i++) {
  6402. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6403. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6404. this.addLineTo(x, y);
  6405. currentAngle += increment;
  6406. }
  6407. return this;
  6408. };
  6409. /**
  6410. * Closes the Path2.
  6411. * Returns the Path2.
  6412. */
  6413. Path2.prototype.close = function () {
  6414. this.closed = true;
  6415. return this;
  6416. };
  6417. /**
  6418. * Returns the Path2 total length (float).
  6419. */
  6420. Path2.prototype.length = function () {
  6421. var result = this._length;
  6422. if (!this.closed) {
  6423. var lastPoint = this._points[this._points.length - 1];
  6424. var firstPoint = this._points[0];
  6425. result += (firstPoint.subtract(lastPoint).length());
  6426. }
  6427. return result;
  6428. };
  6429. /**
  6430. * Returns the Path2 internal array of points.
  6431. */
  6432. Path2.prototype.getPoints = function () {
  6433. return this._points;
  6434. };
  6435. /**
  6436. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6437. */
  6438. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6439. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6440. return Vector2.Zero();
  6441. }
  6442. var lengthPosition = normalizedLengthPosition * this.length();
  6443. var previousOffset = 0;
  6444. for (var i = 0; i < this._points.length; i++) {
  6445. var j = (i + 1) % this._points.length;
  6446. var a = this._points[i];
  6447. var b = this._points[j];
  6448. var bToA = b.subtract(a);
  6449. var nextOffset = (bToA.length() + previousOffset);
  6450. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6451. var dir = bToA.normalize();
  6452. var localOffset = lengthPosition - previousOffset;
  6453. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6454. }
  6455. previousOffset = nextOffset;
  6456. }
  6457. return Vector2.Zero();
  6458. };
  6459. /**
  6460. * Returns a new Path2 starting at the coordinates (x, y).
  6461. */
  6462. Path2.StartingAt = function (x, y) {
  6463. return new Path2(x, y);
  6464. };
  6465. return Path2;
  6466. }());
  6467. BABYLON.Path2 = Path2;
  6468. var Path3D = /** @class */ (function () {
  6469. /**
  6470. * new Path3D(path, normal, raw)
  6471. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6472. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6473. * path : an array of Vector3, the curve axis of the Path3D
  6474. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6475. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6476. */
  6477. function Path3D(path, firstNormal, raw) {
  6478. if (firstNormal === void 0) { firstNormal = null; }
  6479. this.path = path;
  6480. this._curve = new Array();
  6481. this._distances = new Array();
  6482. this._tangents = new Array();
  6483. this._normals = new Array();
  6484. this._binormals = new Array();
  6485. for (var p = 0; p < path.length; p++) {
  6486. this._curve[p] = path[p].clone(); // hard copy
  6487. }
  6488. this._raw = raw || false;
  6489. this._compute(firstNormal);
  6490. }
  6491. /**
  6492. * Returns the Path3D array of successive Vector3 designing its curve.
  6493. */
  6494. Path3D.prototype.getCurve = function () {
  6495. return this._curve;
  6496. };
  6497. /**
  6498. * Returns an array populated with tangent vectors on each Path3D curve point.
  6499. */
  6500. Path3D.prototype.getTangents = function () {
  6501. return this._tangents;
  6502. };
  6503. /**
  6504. * Returns an array populated with normal vectors on each Path3D curve point.
  6505. */
  6506. Path3D.prototype.getNormals = function () {
  6507. return this._normals;
  6508. };
  6509. /**
  6510. * Returns an array populated with binormal vectors on each Path3D curve point.
  6511. */
  6512. Path3D.prototype.getBinormals = function () {
  6513. return this._binormals;
  6514. };
  6515. /**
  6516. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6517. */
  6518. Path3D.prototype.getDistances = function () {
  6519. return this._distances;
  6520. };
  6521. /**
  6522. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6523. * Returns the same object updated.
  6524. */
  6525. Path3D.prototype.update = function (path, firstNormal) {
  6526. if (firstNormal === void 0) { firstNormal = null; }
  6527. for (var p = 0; p < path.length; p++) {
  6528. this._curve[p].x = path[p].x;
  6529. this._curve[p].y = path[p].y;
  6530. this._curve[p].z = path[p].z;
  6531. }
  6532. this._compute(firstNormal);
  6533. return this;
  6534. };
  6535. // private function compute() : computes tangents, normals and binormals
  6536. Path3D.prototype._compute = function (firstNormal) {
  6537. var l = this._curve.length;
  6538. // first and last tangents
  6539. this._tangents[0] = this._getFirstNonNullVector(0);
  6540. if (!this._raw) {
  6541. this._tangents[0].normalize();
  6542. }
  6543. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6544. if (!this._raw) {
  6545. this._tangents[l - 1].normalize();
  6546. }
  6547. // normals and binormals at first point : arbitrary vector with _normalVector()
  6548. var tg0 = this._tangents[0];
  6549. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6550. this._normals[0] = pp0;
  6551. if (!this._raw) {
  6552. this._normals[0].normalize();
  6553. }
  6554. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6555. if (!this._raw) {
  6556. this._binormals[0].normalize();
  6557. }
  6558. this._distances[0] = 0.0;
  6559. // normals and binormals : next points
  6560. var prev; // previous vector (segment)
  6561. var cur; // current vector (segment)
  6562. var curTang; // current tangent
  6563. // previous normal
  6564. var prevBinor; // previous binormal
  6565. for (var i = 1; i < l; i++) {
  6566. // tangents
  6567. prev = this._getLastNonNullVector(i);
  6568. if (i < l - 1) {
  6569. cur = this._getFirstNonNullVector(i);
  6570. this._tangents[i] = prev.add(cur);
  6571. this._tangents[i].normalize();
  6572. }
  6573. this._distances[i] = this._distances[i - 1] + prev.length();
  6574. // normals and binormals
  6575. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6576. curTang = this._tangents[i];
  6577. prevBinor = this._binormals[i - 1];
  6578. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6579. if (!this._raw) {
  6580. this._normals[i].normalize();
  6581. }
  6582. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6583. if (!this._raw) {
  6584. this._binormals[i].normalize();
  6585. }
  6586. }
  6587. };
  6588. // private function getFirstNonNullVector(index)
  6589. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6590. Path3D.prototype._getFirstNonNullVector = function (index) {
  6591. var i = 1;
  6592. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6593. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6594. i++;
  6595. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6596. }
  6597. return nNVector;
  6598. };
  6599. // private function getLastNonNullVector(index)
  6600. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6601. Path3D.prototype._getLastNonNullVector = function (index) {
  6602. var i = 1;
  6603. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6604. while (nLVector.length() === 0 && index > i + 1) {
  6605. i++;
  6606. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6607. }
  6608. return nLVector;
  6609. };
  6610. // private function normalVector(v0, vt, va) :
  6611. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6612. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6613. Path3D.prototype._normalVector = function (v0, vt, va) {
  6614. var normal0;
  6615. var tgl = vt.length();
  6616. if (tgl === 0.0) {
  6617. tgl = 1.0;
  6618. }
  6619. if (va === undefined || va === null) {
  6620. var point;
  6621. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6622. point = new Vector3(0.0, -1.0, 0.0);
  6623. }
  6624. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6625. point = new Vector3(1.0, 0.0, 0.0);
  6626. }
  6627. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6628. point = new Vector3(0.0, 0.0, 1.0);
  6629. }
  6630. else {
  6631. point = Vector3.Zero();
  6632. }
  6633. normal0 = Vector3.Cross(vt, point);
  6634. }
  6635. else {
  6636. normal0 = Vector3.Cross(vt, va);
  6637. Vector3.CrossToRef(normal0, vt, normal0);
  6638. }
  6639. normal0.normalize();
  6640. return normal0;
  6641. };
  6642. return Path3D;
  6643. }());
  6644. BABYLON.Path3D = Path3D;
  6645. var Curve3 = /** @class */ (function () {
  6646. /**
  6647. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6648. * A Curve3 is designed from a series of successive Vector3.
  6649. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6650. */
  6651. function Curve3(points) {
  6652. this._length = 0.0;
  6653. this._points = points;
  6654. this._length = this._computeLength(points);
  6655. }
  6656. /**
  6657. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6658. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6659. * @param v1 (Vector3) the control point
  6660. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6661. * @param nbPoints (integer) the wanted number of points in the curve
  6662. */
  6663. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6664. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6665. var bez = new Array();
  6666. var equation = function (t, val0, val1, val2) {
  6667. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6668. return res;
  6669. };
  6670. for (var i = 0; i <= nbPoints; i++) {
  6671. 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)));
  6672. }
  6673. return new Curve3(bez);
  6674. };
  6675. /**
  6676. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6677. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6678. * @param v1 (Vector3) the first control point
  6679. * @param v2 (Vector3) the second control point
  6680. * @param v3 (Vector3) the end point of the Cubic Bezier
  6681. * @param nbPoints (integer) the wanted number of points in the curve
  6682. */
  6683. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6684. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6685. var bez = new Array();
  6686. var equation = function (t, val0, val1, val2, val3) {
  6687. 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;
  6688. return res;
  6689. };
  6690. for (var i = 0; i <= nbPoints; i++) {
  6691. 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)));
  6692. }
  6693. return new Curve3(bez);
  6694. };
  6695. /**
  6696. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6697. * @param p1 (Vector3) the origin point of the Hermite Spline
  6698. * @param t1 (Vector3) the tangent vector at the origin point
  6699. * @param p2 (Vector3) the end point of the Hermite Spline
  6700. * @param t2 (Vector3) the tangent vector at the end point
  6701. * @param nbPoints (integer) the wanted number of points in the curve
  6702. */
  6703. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6704. var hermite = new Array();
  6705. var step = 1.0 / nbPoints;
  6706. for (var i = 0; i <= nbPoints; i++) {
  6707. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6708. }
  6709. return new Curve3(hermite);
  6710. };
  6711. /**
  6712. * Returns a Curve3 object along a CatmullRom Spline curve :
  6713. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6714. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6715. */
  6716. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6717. var totalPoints = new Array();
  6718. totalPoints.push(points[0].clone());
  6719. Array.prototype.push.apply(totalPoints, points);
  6720. totalPoints.push(points[points.length - 1].clone());
  6721. var catmullRom = new Array();
  6722. var step = 1.0 / nbPoints;
  6723. var amount = 0.0;
  6724. for (var i = 0; i < totalPoints.length - 3; i++) {
  6725. amount = 0;
  6726. for (var c = 0; c < nbPoints; c++) {
  6727. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6728. amount += step;
  6729. }
  6730. }
  6731. i--;
  6732. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6733. return new Curve3(catmullRom);
  6734. };
  6735. /**
  6736. * Returns the Curve3 stored array of successive Vector3
  6737. */
  6738. Curve3.prototype.getPoints = function () {
  6739. return this._points;
  6740. };
  6741. /**
  6742. * Returns the computed length (float) of the curve.
  6743. */
  6744. Curve3.prototype.length = function () {
  6745. return this._length;
  6746. };
  6747. /**
  6748. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6749. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6750. * curveA and curveB keep unchanged.
  6751. */
  6752. Curve3.prototype.continue = function (curve) {
  6753. var lastPoint = this._points[this._points.length - 1];
  6754. var continuedPoints = this._points.slice();
  6755. var curvePoints = curve.getPoints();
  6756. for (var i = 1; i < curvePoints.length; i++) {
  6757. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6758. }
  6759. var continuedCurve = new Curve3(continuedPoints);
  6760. return continuedCurve;
  6761. };
  6762. Curve3.prototype._computeLength = function (path) {
  6763. var l = 0;
  6764. for (var i = 1; i < path.length; i++) {
  6765. l += (path[i].subtract(path[i - 1])).length();
  6766. }
  6767. return l;
  6768. };
  6769. return Curve3;
  6770. }());
  6771. BABYLON.Curve3 = Curve3;
  6772. // Vertex formats
  6773. var PositionNormalVertex = /** @class */ (function () {
  6774. function PositionNormalVertex(position, normal) {
  6775. if (position === void 0) { position = Vector3.Zero(); }
  6776. if (normal === void 0) { normal = Vector3.Up(); }
  6777. this.position = position;
  6778. this.normal = normal;
  6779. }
  6780. PositionNormalVertex.prototype.clone = function () {
  6781. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6782. };
  6783. return PositionNormalVertex;
  6784. }());
  6785. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6786. var PositionNormalTextureVertex = /** @class */ (function () {
  6787. function PositionNormalTextureVertex(position, normal, uv) {
  6788. if (position === void 0) { position = Vector3.Zero(); }
  6789. if (normal === void 0) { normal = Vector3.Up(); }
  6790. if (uv === void 0) { uv = Vector2.Zero(); }
  6791. this.position = position;
  6792. this.normal = normal;
  6793. this.uv = uv;
  6794. }
  6795. PositionNormalTextureVertex.prototype.clone = function () {
  6796. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6797. };
  6798. return PositionNormalTextureVertex;
  6799. }());
  6800. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6801. // Temporary pre-allocated objects for engine internal use
  6802. // usage in any internal function :
  6803. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6804. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6805. var Tmp = /** @class */ (function () {
  6806. function Tmp() {
  6807. }
  6808. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6809. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6810. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6811. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6812. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6813. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6814. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6815. Matrix.Zero(), Matrix.Zero(),
  6816. Matrix.Zero(), Matrix.Zero(),
  6817. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6818. return Tmp;
  6819. }());
  6820. BABYLON.Tmp = Tmp;
  6821. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6822. var MathTmp = /** @class */ (function () {
  6823. function MathTmp() {
  6824. }
  6825. MathTmp.Vector3 = [Vector3.Zero()];
  6826. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6827. MathTmp.Quaternion = [Quaternion.Zero()];
  6828. return MathTmp;
  6829. }());
  6830. })(BABYLON || (BABYLON = {}));
  6831. //# sourceMappingURL=babylon.math.js.map
  6832. "use strict";
  6833. var BABYLON;
  6834. (function (BABYLON) {
  6835. var Scalar = /** @class */ (function () {
  6836. function Scalar() {
  6837. }
  6838. /**
  6839. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6840. */
  6841. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6842. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6843. var num = a - b;
  6844. return -epsilon <= num && num <= epsilon;
  6845. };
  6846. /**
  6847. * Returns a string : the upper case translation of the number i to hexadecimal.
  6848. */
  6849. Scalar.ToHex = function (i) {
  6850. var str = i.toString(16);
  6851. if (i <= 15) {
  6852. return ("0" + str).toUpperCase();
  6853. }
  6854. return str.toUpperCase();
  6855. };
  6856. /**
  6857. * Returns -1 if value is negative and +1 is value is positive.
  6858. * Returns the value itself if it's equal to zero.
  6859. */
  6860. Scalar.Sign = function (value) {
  6861. value = +value; // convert to a number
  6862. if (value === 0 || isNaN(value))
  6863. return value;
  6864. return value > 0 ? 1 : -1;
  6865. };
  6866. /**
  6867. * Returns the value itself if it's between min and max.
  6868. * Returns min if the value is lower than min.
  6869. * Returns max if the value is greater than max.
  6870. */
  6871. Scalar.Clamp = function (value, min, max) {
  6872. if (min === void 0) { min = 0; }
  6873. if (max === void 0) { max = 1; }
  6874. return Math.min(max, Math.max(min, value));
  6875. };
  6876. /**
  6877. * Returns the log2 of value.
  6878. */
  6879. Scalar.Log2 = function (value) {
  6880. return Math.log(value) * Math.LOG2E;
  6881. };
  6882. /**
  6883. * Loops the value, so that it is never larger than length and never smaller than 0.
  6884. *
  6885. * This is similar to the modulo operator but it works with floating point numbers.
  6886. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6887. * With t = 5 and length = 2.5, the result would be 0.0.
  6888. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6889. */
  6890. Scalar.Repeat = function (value, length) {
  6891. return value - Math.floor(value / length) * length;
  6892. };
  6893. /**
  6894. * Normalize the value between 0.0 and 1.0 using min and max values
  6895. */
  6896. Scalar.Normalize = function (value, min, max) {
  6897. return (value - min) / (max - min);
  6898. };
  6899. /**
  6900. * Denormalize the value from 0.0 and 1.0 using min and max values
  6901. */
  6902. Scalar.Denormalize = function (normalized, min, max) {
  6903. return (normalized * (max - min) + min);
  6904. };
  6905. /**
  6906. * Calculates the shortest difference between two given angles given in degrees.
  6907. */
  6908. Scalar.DeltaAngle = function (current, target) {
  6909. var num = Scalar.Repeat(target - current, 360.0);
  6910. if (num > 180.0) {
  6911. num -= 360.0;
  6912. }
  6913. return num;
  6914. };
  6915. /**
  6916. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6917. *
  6918. * The returned value will move back and forth between 0 and length
  6919. */
  6920. Scalar.PingPong = function (tx, length) {
  6921. var t = Scalar.Repeat(tx, length * 2.0);
  6922. return length - Math.abs(t - length);
  6923. };
  6924. /**
  6925. * Interpolates between min and max with smoothing at the limits.
  6926. *
  6927. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6928. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6929. */
  6930. Scalar.SmoothStep = function (from, to, tx) {
  6931. var t = Scalar.Clamp(tx);
  6932. t = -2.0 * t * t * t + 3.0 * t * t;
  6933. return to * t + from * (1.0 - t);
  6934. };
  6935. /**
  6936. * Moves a value current towards target.
  6937. *
  6938. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6939. * Negative values of maxDelta pushes the value away from target.
  6940. */
  6941. Scalar.MoveTowards = function (current, target, maxDelta) {
  6942. var result = 0;
  6943. if (Math.abs(target - current) <= maxDelta) {
  6944. result = target;
  6945. }
  6946. else {
  6947. result = current + Scalar.Sign(target - current) * maxDelta;
  6948. }
  6949. return result;
  6950. };
  6951. /**
  6952. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6953. *
  6954. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6955. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6956. */
  6957. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6958. var num = Scalar.DeltaAngle(current, target);
  6959. var result = 0;
  6960. if (-maxDelta < num && num < maxDelta) {
  6961. result = target;
  6962. }
  6963. else {
  6964. target = current + num;
  6965. result = Scalar.MoveTowards(current, target, maxDelta);
  6966. }
  6967. return result;
  6968. };
  6969. /**
  6970. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6971. */
  6972. Scalar.Lerp = function (start, end, amount) {
  6973. return start + ((end - start) * amount);
  6974. };
  6975. /**
  6976. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6977. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6978. */
  6979. Scalar.LerpAngle = function (start, end, amount) {
  6980. var num = Scalar.Repeat(end - start, 360.0);
  6981. if (num > 180.0) {
  6982. num -= 360.0;
  6983. }
  6984. return start + num * Scalar.Clamp(amount);
  6985. };
  6986. /**
  6987. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  6988. */
  6989. Scalar.InverseLerp = function (a, b, value) {
  6990. var result = 0;
  6991. if (a != b) {
  6992. result = Scalar.Clamp((value - a) / (b - a));
  6993. }
  6994. else {
  6995. result = 0.0;
  6996. }
  6997. return result;
  6998. };
  6999. /**
  7000. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7001. */
  7002. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7003. var squared = amount * amount;
  7004. var cubed = amount * squared;
  7005. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7006. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7007. var part3 = (cubed - (2.0 * squared)) + amount;
  7008. var part4 = cubed - squared;
  7009. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7010. };
  7011. /**
  7012. * Returns a random float number between and min and max values
  7013. */
  7014. Scalar.RandomRange = function (min, max) {
  7015. if (min === max)
  7016. return min;
  7017. return ((Math.random() * (max - min)) + min);
  7018. };
  7019. /**
  7020. * This function returns percentage of a number in a given range.
  7021. *
  7022. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7023. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7024. */
  7025. Scalar.RangeToPercent = function (number, min, max) {
  7026. return ((number - min) / (max - min));
  7027. };
  7028. /**
  7029. * This function returns number that corresponds to the percentage in a given range.
  7030. *
  7031. * PercentToRange(0.34,0,100) will return 34.
  7032. */
  7033. Scalar.PercentToRange = function (percent, min, max) {
  7034. return ((max - min) * percent + min);
  7035. };
  7036. /**
  7037. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7038. * @param angle The angle to normalize in radian.
  7039. * @return The converted angle.
  7040. */
  7041. Scalar.NormalizeRadians = function (angle) {
  7042. // More precise but slower version kept for reference.
  7043. // angle = angle % Tools.TwoPi;
  7044. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7045. //if (angle > Math.PI) {
  7046. // angle -= Tools.TwoPi;
  7047. //}
  7048. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7049. return angle;
  7050. };
  7051. /**
  7052. * Two pi constants convenient for computation.
  7053. */
  7054. Scalar.TwoPi = Math.PI * 2;
  7055. return Scalar;
  7056. }());
  7057. BABYLON.Scalar = Scalar;
  7058. })(BABYLON || (BABYLON = {}));
  7059. //# sourceMappingURL=babylon.math.scalar.js.map
  7060. "use strict";
  7061. //# sourceMappingURL=babylon.mixins.js.map
  7062. "use strict";
  7063. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7064. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7065. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7066. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7067. //# sourceMappingURL=babylon.webgl2.js.map
  7068. "use strict";
  7069. var BABYLON;
  7070. (function (BABYLON) {
  7071. var __decoratorInitialStore = {};
  7072. var __mergedStore = {};
  7073. var _copySource = function (creationFunction, source, instanciate) {
  7074. var destination = creationFunction();
  7075. // Tags
  7076. if (BABYLON.Tags) {
  7077. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7078. }
  7079. var classStore = getMergedStore(destination);
  7080. // Properties
  7081. for (var property in classStore) {
  7082. var propertyDescriptor = classStore[property];
  7083. var sourceProperty = source[property];
  7084. var propertyType = propertyDescriptor.type;
  7085. if (sourceProperty !== undefined && sourceProperty !== null) {
  7086. switch (propertyType) {
  7087. case 0: // Value
  7088. case 6: // Mesh reference
  7089. case 11:// Camera reference
  7090. destination[property] = sourceProperty;
  7091. break;
  7092. case 1:// Texture
  7093. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7094. break;
  7095. case 2: // Color3
  7096. case 3: // FresnelParameters
  7097. case 4: // Vector2
  7098. case 5: // Vector3
  7099. case 7: // Color Curves
  7100. case 10:// Quaternion
  7101. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7102. break;
  7103. }
  7104. }
  7105. }
  7106. return destination;
  7107. };
  7108. function getDirectStore(target) {
  7109. var classKey = target.getClassName();
  7110. if (!__decoratorInitialStore[classKey]) {
  7111. __decoratorInitialStore[classKey] = {};
  7112. }
  7113. return __decoratorInitialStore[classKey];
  7114. }
  7115. /**
  7116. * Return the list of properties flagged as serializable
  7117. * @param target: host object
  7118. */
  7119. function getMergedStore(target) {
  7120. var classKey = target.getClassName();
  7121. if (__mergedStore[classKey]) {
  7122. return __mergedStore[classKey];
  7123. }
  7124. __mergedStore[classKey] = {};
  7125. var store = __mergedStore[classKey];
  7126. var currentTarget = target;
  7127. var currentKey = classKey;
  7128. while (currentKey) {
  7129. var initialStore = __decoratorInitialStore[currentKey];
  7130. for (var property in initialStore) {
  7131. store[property] = initialStore[property];
  7132. }
  7133. var parent_1 = void 0;
  7134. var done = false;
  7135. do {
  7136. parent_1 = Object.getPrototypeOf(currentTarget);
  7137. if (!parent_1.getClassName) {
  7138. done = true;
  7139. break;
  7140. }
  7141. if (parent_1.getClassName() !== currentKey) {
  7142. break;
  7143. }
  7144. currentTarget = parent_1;
  7145. } while (parent_1);
  7146. if (done) {
  7147. break;
  7148. }
  7149. currentKey = parent_1.getClassName();
  7150. currentTarget = parent_1;
  7151. }
  7152. return store;
  7153. }
  7154. function generateSerializableMember(type, sourceName) {
  7155. return function (target, propertyKey) {
  7156. var classStore = getDirectStore(target);
  7157. if (!classStore[propertyKey]) {
  7158. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7159. }
  7160. };
  7161. }
  7162. function generateExpandMember(setCallback, targetKey) {
  7163. if (targetKey === void 0) { targetKey = null; }
  7164. return function (target, propertyKey) {
  7165. var key = targetKey || ("_" + propertyKey);
  7166. Object.defineProperty(target, propertyKey, {
  7167. get: function () {
  7168. return this[key];
  7169. },
  7170. set: function (value) {
  7171. if (this[key] === value) {
  7172. return;
  7173. }
  7174. this[key] = value;
  7175. target[setCallback].apply(this);
  7176. },
  7177. enumerable: true,
  7178. configurable: true
  7179. });
  7180. };
  7181. }
  7182. function expandToProperty(callback, targetKey) {
  7183. if (targetKey === void 0) { targetKey = null; }
  7184. return generateExpandMember(callback, targetKey);
  7185. }
  7186. BABYLON.expandToProperty = expandToProperty;
  7187. function serialize(sourceName) {
  7188. return generateSerializableMember(0, sourceName); // value member
  7189. }
  7190. BABYLON.serialize = serialize;
  7191. function serializeAsTexture(sourceName) {
  7192. return generateSerializableMember(1, sourceName); // texture member
  7193. }
  7194. BABYLON.serializeAsTexture = serializeAsTexture;
  7195. function serializeAsColor3(sourceName) {
  7196. return generateSerializableMember(2, sourceName); // color3 member
  7197. }
  7198. BABYLON.serializeAsColor3 = serializeAsColor3;
  7199. function serializeAsFresnelParameters(sourceName) {
  7200. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7201. }
  7202. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7203. function serializeAsVector2(sourceName) {
  7204. return generateSerializableMember(4, sourceName); // vector2 member
  7205. }
  7206. BABYLON.serializeAsVector2 = serializeAsVector2;
  7207. function serializeAsVector3(sourceName) {
  7208. return generateSerializableMember(5, sourceName); // vector3 member
  7209. }
  7210. BABYLON.serializeAsVector3 = serializeAsVector3;
  7211. function serializeAsMeshReference(sourceName) {
  7212. return generateSerializableMember(6, sourceName); // mesh reference member
  7213. }
  7214. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7215. function serializeAsColorCurves(sourceName) {
  7216. return generateSerializableMember(7, sourceName); // color curves
  7217. }
  7218. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7219. function serializeAsColor4(sourceName) {
  7220. return generateSerializableMember(8, sourceName); // color 4
  7221. }
  7222. BABYLON.serializeAsColor4 = serializeAsColor4;
  7223. function serializeAsImageProcessingConfiguration(sourceName) {
  7224. return generateSerializableMember(9, sourceName); // image processing
  7225. }
  7226. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7227. function serializeAsQuaternion(sourceName) {
  7228. return generateSerializableMember(10, sourceName); // quaternion member
  7229. }
  7230. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7231. /**
  7232. * Decorator used to define property that can be serialized as reference to a camera
  7233. * @param sourceName defines the name of the property to decorate
  7234. */
  7235. function serializeAsCameraReference(sourceName) {
  7236. return generateSerializableMember(11, sourceName); // camera reference member
  7237. }
  7238. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7239. var SerializationHelper = /** @class */ (function () {
  7240. function SerializationHelper() {
  7241. }
  7242. SerializationHelper.Serialize = function (entity, serializationObject) {
  7243. if (!serializationObject) {
  7244. serializationObject = {};
  7245. }
  7246. // Tags
  7247. if (BABYLON.Tags) {
  7248. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7249. }
  7250. var serializedProperties = getMergedStore(entity);
  7251. // Properties
  7252. for (var property in serializedProperties) {
  7253. var propertyDescriptor = serializedProperties[property];
  7254. var targetPropertyName = propertyDescriptor.sourceName || property;
  7255. var propertyType = propertyDescriptor.type;
  7256. var sourceProperty = entity[property];
  7257. if (sourceProperty !== undefined && sourceProperty !== null) {
  7258. switch (propertyType) {
  7259. case 0:// Value
  7260. serializationObject[targetPropertyName] = sourceProperty;
  7261. break;
  7262. case 1:// Texture
  7263. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7264. break;
  7265. case 2:// Color3
  7266. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7267. break;
  7268. case 3:// FresnelParameters
  7269. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7270. break;
  7271. case 4:// Vector2
  7272. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7273. break;
  7274. case 5:// Vector3
  7275. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7276. break;
  7277. case 6:// Mesh reference
  7278. serializationObject[targetPropertyName] = sourceProperty.id;
  7279. break;
  7280. case 7:// Color Curves
  7281. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7282. break;
  7283. case 8:// Color 4
  7284. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7285. break;
  7286. case 9:// Image Processing
  7287. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7288. break;
  7289. case 10:// Quaternion
  7290. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7291. break;
  7292. case 11:// Camera reference
  7293. serializationObject[targetPropertyName] = sourceProperty.id;
  7294. break;
  7295. }
  7296. }
  7297. }
  7298. return serializationObject;
  7299. };
  7300. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7301. if (rootUrl === void 0) { rootUrl = null; }
  7302. var destination = creationFunction();
  7303. if (!rootUrl) {
  7304. rootUrl = "";
  7305. }
  7306. // Tags
  7307. if (BABYLON.Tags) {
  7308. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7309. }
  7310. var classStore = getMergedStore(destination);
  7311. // Properties
  7312. for (var property in classStore) {
  7313. var propertyDescriptor = classStore[property];
  7314. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7315. var propertyType = propertyDescriptor.type;
  7316. if (sourceProperty !== undefined && sourceProperty !== null) {
  7317. var dest = destination;
  7318. switch (propertyType) {
  7319. case 0:// Value
  7320. dest[property] = sourceProperty;
  7321. break;
  7322. case 1:// Texture
  7323. if (scene) {
  7324. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7325. }
  7326. break;
  7327. case 2:// Color3
  7328. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7329. break;
  7330. case 3:// FresnelParameters
  7331. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7332. break;
  7333. case 4:// Vector2
  7334. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7335. break;
  7336. case 5:// Vector3
  7337. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7338. break;
  7339. case 6:// Mesh reference
  7340. if (scene) {
  7341. dest[property] = scene.getLastMeshByID(sourceProperty);
  7342. }
  7343. break;
  7344. case 7:// Color Curves
  7345. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7346. break;
  7347. case 8:// Color 4
  7348. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7349. break;
  7350. case 9:// Image Processing
  7351. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7352. break;
  7353. case 10:// Quaternion
  7354. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7355. break;
  7356. case 11:// Camera reference
  7357. if (scene) {
  7358. dest[property] = scene.getCameraByID(sourceProperty);
  7359. }
  7360. break;
  7361. }
  7362. }
  7363. }
  7364. return destination;
  7365. };
  7366. SerializationHelper.Clone = function (creationFunction, source) {
  7367. return _copySource(creationFunction, source, false);
  7368. };
  7369. SerializationHelper.Instanciate = function (creationFunction, source) {
  7370. return _copySource(creationFunction, source, true);
  7371. };
  7372. return SerializationHelper;
  7373. }());
  7374. BABYLON.SerializationHelper = SerializationHelper;
  7375. })(BABYLON || (BABYLON = {}));
  7376. //# sourceMappingURL=babylon.decorators.js.map
  7377. "use strict";
  7378. var BABYLON;
  7379. (function (BABYLON) {
  7380. /**
  7381. * Wrapper class for promise with external resolve and reject.
  7382. */
  7383. var Deferred = /** @class */ (function () {
  7384. /**
  7385. * Constructor for this deferred object.
  7386. */
  7387. function Deferred() {
  7388. var _this = this;
  7389. this.promise = new Promise(function (resolve, reject) {
  7390. _this._resolve = resolve;
  7391. _this._reject = reject;
  7392. });
  7393. }
  7394. Object.defineProperty(Deferred.prototype, "resolve", {
  7395. /**
  7396. * The resolve method of the promise associated with this deferred object.
  7397. */
  7398. get: function () {
  7399. return this._resolve;
  7400. },
  7401. enumerable: true,
  7402. configurable: true
  7403. });
  7404. Object.defineProperty(Deferred.prototype, "reject", {
  7405. /**
  7406. * The reject method of the promise associated with this deferred object.
  7407. */
  7408. get: function () {
  7409. return this._reject;
  7410. },
  7411. enumerable: true,
  7412. configurable: true
  7413. });
  7414. return Deferred;
  7415. }());
  7416. BABYLON.Deferred = Deferred;
  7417. })(BABYLON || (BABYLON = {}));
  7418. //# sourceMappingURL=babylon.deferred.js.map
  7419. "use strict";
  7420. var BABYLON;
  7421. (function (BABYLON) {
  7422. /**
  7423. * A class serves as a medium between the observable and its observers
  7424. */
  7425. var EventState = /** @class */ (function () {
  7426. /**
  7427. * Create a new EventState
  7428. * @param mask defines the mask associated with this state
  7429. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7430. * @param target defines the original target of the state
  7431. * @param currentTarget defines the current target of the state
  7432. */
  7433. function EventState(mask, skipNextObservers, target, currentTarget) {
  7434. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7435. this.initalize(mask, skipNextObservers, target, currentTarget);
  7436. }
  7437. /**
  7438. * Initialize the current event state
  7439. * @param mask defines the mask associated with this state
  7440. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7441. * @param target defines the original target of the state
  7442. * @param currentTarget defines the current target of the state
  7443. * @returns the current event state
  7444. */
  7445. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7446. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7447. this.mask = mask;
  7448. this.skipNextObservers = skipNextObservers;
  7449. this.target = target;
  7450. this.currentTarget = currentTarget;
  7451. return this;
  7452. };
  7453. return EventState;
  7454. }());
  7455. BABYLON.EventState = EventState;
  7456. /**
  7457. * Represent an Observer registered to a given Observable object.
  7458. */
  7459. var Observer = /** @class */ (function () {
  7460. /**
  7461. * Creates a new observer
  7462. * @param callback defines the callback to call when the observer is notified
  7463. * @param mask defines the mask of the observer (used to filter notifications)
  7464. * @param scope defines the current scope used to restore the JS context
  7465. */
  7466. function Observer(
  7467. /**
  7468. * Defines the callback to call when the observer is notified
  7469. */
  7470. callback,
  7471. /**
  7472. * Defines the mask of the observer (used to filter notifications)
  7473. */
  7474. mask,
  7475. /**
  7476. * Defines the current scope used to restore the JS context
  7477. */
  7478. scope) {
  7479. if (scope === void 0) { scope = null; }
  7480. this.callback = callback;
  7481. this.mask = mask;
  7482. this.scope = scope;
  7483. /** @ignore */
  7484. this._willBeUnregistered = false;
  7485. /**
  7486. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7487. */
  7488. this.unregisterOnNextCall = false;
  7489. }
  7490. return Observer;
  7491. }());
  7492. BABYLON.Observer = Observer;
  7493. /**
  7494. * Represent a list of observers registered to multiple Observables object.
  7495. */
  7496. var MultiObserver = /** @class */ (function () {
  7497. function MultiObserver() {
  7498. }
  7499. /**
  7500. * Release associated resources
  7501. */
  7502. MultiObserver.prototype.dispose = function () {
  7503. if (this._observers && this._observables) {
  7504. for (var index = 0; index < this._observers.length; index++) {
  7505. this._observables[index].remove(this._observers[index]);
  7506. }
  7507. }
  7508. this._observers = null;
  7509. this._observables = null;
  7510. };
  7511. /**
  7512. * Raise a callback when one of the observable will notify
  7513. * @param observables defines a list of observables to watch
  7514. * @param callback defines the callback to call on notification
  7515. * @param mask defines the mask used to filter notifications
  7516. * @param scope defines the current scope used to restore the JS context
  7517. * @returns the new MultiObserver
  7518. */
  7519. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7520. if (mask === void 0) { mask = -1; }
  7521. if (scope === void 0) { scope = null; }
  7522. var result = new MultiObserver();
  7523. result._observers = new Array();
  7524. result._observables = observables;
  7525. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7526. var observable = observables_1[_i];
  7527. var observer = observable.add(callback, mask, false, scope);
  7528. if (observer) {
  7529. result._observers.push(observer);
  7530. }
  7531. }
  7532. return result;
  7533. };
  7534. return MultiObserver;
  7535. }());
  7536. BABYLON.MultiObserver = MultiObserver;
  7537. /**
  7538. * The Observable class is a simple implementation of the Observable pattern.
  7539. *
  7540. * 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.
  7541. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7542. * 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).
  7543. * 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.
  7544. */
  7545. var Observable = /** @class */ (function () {
  7546. /**
  7547. * Creates a new observable
  7548. * @param onObserverAdded defines a callback to call when a new observer is added
  7549. */
  7550. function Observable(onObserverAdded) {
  7551. this._observers = new Array();
  7552. this._eventState = new EventState(0);
  7553. if (onObserverAdded) {
  7554. this._onObserverAdded = onObserverAdded;
  7555. }
  7556. }
  7557. /**
  7558. * Create a new Observer with the specified callback
  7559. * @param callback the callback that will be executed for that Observer
  7560. * @param mask the mask used to filter observers
  7561. * @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.
  7562. * @param scope optional scope for the callback to be called from
  7563. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7564. * @returns the new observer created for the callback
  7565. */
  7566. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7567. if (mask === void 0) { mask = -1; }
  7568. if (insertFirst === void 0) { insertFirst = false; }
  7569. if (scope === void 0) { scope = null; }
  7570. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7571. if (!callback) {
  7572. return null;
  7573. }
  7574. var observer = new Observer(callback, mask, scope);
  7575. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7576. if (insertFirst) {
  7577. this._observers.unshift(observer);
  7578. }
  7579. else {
  7580. this._observers.push(observer);
  7581. }
  7582. if (this._onObserverAdded) {
  7583. this._onObserverAdded(observer);
  7584. }
  7585. return observer;
  7586. };
  7587. /**
  7588. * Remove an Observer from the Observable object
  7589. * @param observer the instance of the Observer to remove
  7590. * @returns false if it doesn't belong to this Observable
  7591. */
  7592. Observable.prototype.remove = function (observer) {
  7593. if (!observer) {
  7594. return false;
  7595. }
  7596. var index = this._observers.indexOf(observer);
  7597. if (index !== -1) {
  7598. this._observers.splice(index, 1);
  7599. return true;
  7600. }
  7601. return false;
  7602. };
  7603. /**
  7604. * Remove a callback from the Observable object
  7605. * @param callback the callback to remove
  7606. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7607. * @returns false if it doesn't belong to this Observable
  7608. */
  7609. Observable.prototype.removeCallback = function (callback, scope) {
  7610. for (var index = 0; index < this._observers.length; index++) {
  7611. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7612. this._observers.splice(index, 1);
  7613. return true;
  7614. }
  7615. }
  7616. return false;
  7617. };
  7618. Observable.prototype._deferUnregister = function (observer) {
  7619. var _this = this;
  7620. observer.unregisterOnNextCall = false;
  7621. observer._willBeUnregistered = true;
  7622. BABYLON.Tools.SetImmediate(function () {
  7623. _this.remove(observer);
  7624. });
  7625. };
  7626. /**
  7627. * Notify all Observers by calling their respective callback with the given data
  7628. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7629. * @param eventData defines the data to send to all observers
  7630. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7631. * @param target defines the original target of the state
  7632. * @param currentTarget defines the current target of the state
  7633. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7634. */
  7635. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7636. if (mask === void 0) { mask = -1; }
  7637. if (!this._observers.length) {
  7638. return true;
  7639. }
  7640. var state = this._eventState;
  7641. state.mask = mask;
  7642. state.target = target;
  7643. state.currentTarget = currentTarget;
  7644. state.skipNextObservers = false;
  7645. state.lastReturnValue = eventData;
  7646. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7647. var obs = _a[_i];
  7648. if (obs._willBeUnregistered) {
  7649. continue;
  7650. }
  7651. if (obs.mask & mask) {
  7652. if (obs.scope) {
  7653. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7654. }
  7655. else {
  7656. state.lastReturnValue = obs.callback(eventData, state);
  7657. }
  7658. if (obs.unregisterOnNextCall) {
  7659. this._deferUnregister(obs);
  7660. }
  7661. }
  7662. if (state.skipNextObservers) {
  7663. return false;
  7664. }
  7665. }
  7666. return true;
  7667. };
  7668. /**
  7669. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7670. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7671. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7672. * and it is crucial that all callbacks will be executed.
  7673. * The order of the callbacks is kept, callbacks are not executed parallel.
  7674. *
  7675. * @param eventData The data to be sent to each callback
  7676. * @param mask is used to filter observers defaults to -1
  7677. * @param target defines the callback target (see EventState)
  7678. * @param currentTarget defines he current object in the bubbling phase
  7679. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7680. */
  7681. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7682. var _this = this;
  7683. if (mask === void 0) { mask = -1; }
  7684. // create an empty promise
  7685. var p = Promise.resolve(eventData);
  7686. // no observers? return this promise.
  7687. if (!this._observers.length) {
  7688. return p;
  7689. }
  7690. var state = this._eventState;
  7691. state.mask = mask;
  7692. state.target = target;
  7693. state.currentTarget = currentTarget;
  7694. state.skipNextObservers = false;
  7695. // execute one callback after another (not using Promise.all, the order is important)
  7696. this._observers.forEach(function (obs) {
  7697. if (state.skipNextObservers) {
  7698. return;
  7699. }
  7700. if (obs._willBeUnregistered) {
  7701. return;
  7702. }
  7703. if (obs.mask & mask) {
  7704. if (obs.scope) {
  7705. p = p.then(function (lastReturnedValue) {
  7706. state.lastReturnValue = lastReturnedValue;
  7707. return obs.callback.apply(obs.scope, [eventData, state]);
  7708. });
  7709. }
  7710. else {
  7711. p = p.then(function (lastReturnedValue) {
  7712. state.lastReturnValue = lastReturnedValue;
  7713. return obs.callback(eventData, state);
  7714. });
  7715. }
  7716. if (obs.unregisterOnNextCall) {
  7717. _this._deferUnregister(obs);
  7718. }
  7719. }
  7720. });
  7721. // return the eventData
  7722. return p.then(function () { return eventData; });
  7723. };
  7724. /**
  7725. * Notify a specific observer
  7726. * @param observer defines the observer to notify
  7727. * @param eventData defines the data to be sent to each callback
  7728. * @param mask is used to filter observers defaults to -1
  7729. */
  7730. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7731. if (mask === void 0) { mask = -1; }
  7732. var state = this._eventState;
  7733. state.mask = mask;
  7734. state.skipNextObservers = false;
  7735. observer.callback(eventData, state);
  7736. };
  7737. /**
  7738. * Gets a boolean indicating if the observable has at least one observer
  7739. * @returns true is the Observable has at least one Observer registered
  7740. */
  7741. Observable.prototype.hasObservers = function () {
  7742. return this._observers.length > 0;
  7743. };
  7744. /**
  7745. * Clear the list of observers
  7746. */
  7747. Observable.prototype.clear = function () {
  7748. this._observers = new Array();
  7749. this._onObserverAdded = null;
  7750. };
  7751. /**
  7752. * Clone the current observable
  7753. * @returns a new observable
  7754. */
  7755. Observable.prototype.clone = function () {
  7756. var result = new Observable();
  7757. result._observers = this._observers.slice(0);
  7758. return result;
  7759. };
  7760. /**
  7761. * Does this observable handles observer registered with a given mask
  7762. * @param mask defines the mask to be tested
  7763. * @return whether or not one observer registered with the given mask is handeled
  7764. **/
  7765. Observable.prototype.hasSpecificMask = function (mask) {
  7766. if (mask === void 0) { mask = -1; }
  7767. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7768. var obs = _a[_i];
  7769. if (obs.mask & mask || obs.mask === mask) {
  7770. return true;
  7771. }
  7772. }
  7773. return false;
  7774. };
  7775. return Observable;
  7776. }());
  7777. BABYLON.Observable = Observable;
  7778. })(BABYLON || (BABYLON = {}));
  7779. //# sourceMappingURL=babylon.observable.js.map
  7780. "use strict";
  7781. var BABYLON;
  7782. (function (BABYLON) {
  7783. var SmartArray = /** @class */ (function () {
  7784. function SmartArray(capacity) {
  7785. this.length = 0;
  7786. this.data = new Array(capacity);
  7787. this._id = SmartArray._GlobalId++;
  7788. }
  7789. SmartArray.prototype.push = function (value) {
  7790. this.data[this.length++] = value;
  7791. if (this.length > this.data.length) {
  7792. this.data.length *= 2;
  7793. }
  7794. };
  7795. SmartArray.prototype.forEach = function (func) {
  7796. for (var index = 0; index < this.length; index++) {
  7797. func(this.data[index]);
  7798. }
  7799. };
  7800. SmartArray.prototype.sort = function (compareFn) {
  7801. this.data.sort(compareFn);
  7802. };
  7803. SmartArray.prototype.reset = function () {
  7804. this.length = 0;
  7805. };
  7806. SmartArray.prototype.dispose = function () {
  7807. this.reset();
  7808. if (this.data) {
  7809. this.data.length = 0;
  7810. this.data = [];
  7811. }
  7812. };
  7813. SmartArray.prototype.concat = function (array) {
  7814. if (array.length === 0) {
  7815. return;
  7816. }
  7817. if (this.length + array.length > this.data.length) {
  7818. this.data.length = (this.length + array.length) * 2;
  7819. }
  7820. for (var index = 0; index < array.length; index++) {
  7821. this.data[this.length++] = (array.data || array)[index];
  7822. }
  7823. };
  7824. SmartArray.prototype.indexOf = function (value) {
  7825. var position = this.data.indexOf(value);
  7826. if (position >= this.length) {
  7827. return -1;
  7828. }
  7829. return position;
  7830. };
  7831. SmartArray.prototype.contains = function (value) {
  7832. return this.data.indexOf(value) !== -1;
  7833. };
  7834. // Statics
  7835. SmartArray._GlobalId = 0;
  7836. return SmartArray;
  7837. }());
  7838. BABYLON.SmartArray = SmartArray;
  7839. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7840. __extends(SmartArrayNoDuplicate, _super);
  7841. function SmartArrayNoDuplicate() {
  7842. var _this = _super !== null && _super.apply(this, arguments) || this;
  7843. _this._duplicateId = 0;
  7844. return _this;
  7845. }
  7846. SmartArrayNoDuplicate.prototype.push = function (value) {
  7847. _super.prototype.push.call(this, value);
  7848. if (!value.__smartArrayFlags) {
  7849. value.__smartArrayFlags = {};
  7850. }
  7851. value.__smartArrayFlags[this._id] = this._duplicateId;
  7852. };
  7853. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7854. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7855. return false;
  7856. }
  7857. this.push(value);
  7858. return true;
  7859. };
  7860. SmartArrayNoDuplicate.prototype.reset = function () {
  7861. _super.prototype.reset.call(this);
  7862. this._duplicateId++;
  7863. };
  7864. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7865. if (array.length === 0) {
  7866. return;
  7867. }
  7868. if (this.length + array.length > this.data.length) {
  7869. this.data.length = (this.length + array.length) * 2;
  7870. }
  7871. for (var index = 0; index < array.length; index++) {
  7872. var item = (array.data || array)[index];
  7873. this.pushNoDuplicate(item);
  7874. }
  7875. };
  7876. return SmartArrayNoDuplicate;
  7877. }(SmartArray));
  7878. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7879. })(BABYLON || (BABYLON = {}));
  7880. //# sourceMappingURL=babylon.smartArray.js.map
  7881. "use strict";
  7882. var BABYLON;
  7883. (function (BABYLON) {
  7884. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7885. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7886. var LoadFileError = /** @class */ (function (_super) {
  7887. __extends(LoadFileError, _super);
  7888. function LoadFileError(message, request) {
  7889. var _this = _super.call(this, message) || this;
  7890. _this.request = request;
  7891. _this.name = "LoadFileError";
  7892. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7893. return _this;
  7894. }
  7895. // Polyfill for Object.setPrototypeOf if necessary.
  7896. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7897. return LoadFileError;
  7898. }(Error));
  7899. BABYLON.LoadFileError = LoadFileError;
  7900. var RetryStrategy = /** @class */ (function () {
  7901. function RetryStrategy() {
  7902. }
  7903. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7904. if (maxRetries === void 0) { maxRetries = 3; }
  7905. if (baseInterval === void 0) { baseInterval = 500; }
  7906. return function (url, request, retryIndex) {
  7907. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7908. return -1;
  7909. }
  7910. return Math.pow(2, retryIndex) * baseInterval;
  7911. };
  7912. };
  7913. return RetryStrategy;
  7914. }());
  7915. BABYLON.RetryStrategy = RetryStrategy;
  7916. // Screenshots
  7917. var screenshotCanvas;
  7918. var cloneValue = function (source, destinationObject) {
  7919. if (!source)
  7920. return null;
  7921. if (source instanceof BABYLON.Mesh) {
  7922. return null;
  7923. }
  7924. if (source instanceof BABYLON.SubMesh) {
  7925. return source.clone(destinationObject);
  7926. }
  7927. else if (source.clone) {
  7928. return source.clone();
  7929. }
  7930. return null;
  7931. };
  7932. var Tools = /** @class */ (function () {
  7933. function Tools() {
  7934. }
  7935. /**
  7936. * Interpolates between a and b via alpha
  7937. * @param a The lower value (returned when alpha = 0)
  7938. * @param b The upper value (returned when alpha = 1)
  7939. * @param alpha The interpolation-factor
  7940. * @return The mixed value
  7941. */
  7942. Tools.Mix = function (a, b, alpha) {
  7943. return a * (1 - alpha) + b * alpha;
  7944. };
  7945. Tools.Instantiate = function (className) {
  7946. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7947. return Tools.RegisteredExternalClasses[className];
  7948. }
  7949. var arr = className.split(".");
  7950. var fn = (window || this);
  7951. for (var i = 0, len = arr.length; i < len; i++) {
  7952. fn = fn[arr[i]];
  7953. }
  7954. if (typeof fn !== "function") {
  7955. return null;
  7956. }
  7957. return fn;
  7958. };
  7959. /**
  7960. * Provides a slice function that will work even on IE
  7961. * @param data defines the array to slice
  7962. * @param start defines the start of the data (optional)
  7963. * @param end defines the end of the data (optional)
  7964. * @returns the new sliced array
  7965. */
  7966. Tools.Slice = function (data, start, end) {
  7967. if (data.slice) {
  7968. return data.slice(start, end);
  7969. }
  7970. return Array.prototype.slice.call(data, start, end);
  7971. };
  7972. Tools.SetImmediate = function (action) {
  7973. if (window.setImmediate) {
  7974. window.setImmediate(action);
  7975. }
  7976. else {
  7977. setTimeout(action, 1);
  7978. }
  7979. };
  7980. Tools.IsExponentOfTwo = function (value) {
  7981. var count = 1;
  7982. do {
  7983. count *= 2;
  7984. } while (count < value);
  7985. return count === value;
  7986. };
  7987. /**
  7988. * Find the next highest power of two.
  7989. * @param x Number to start search from.
  7990. * @return Next highest power of two.
  7991. */
  7992. Tools.CeilingPOT = function (x) {
  7993. x--;
  7994. x |= x >> 1;
  7995. x |= x >> 2;
  7996. x |= x >> 4;
  7997. x |= x >> 8;
  7998. x |= x >> 16;
  7999. x++;
  8000. return x;
  8001. };
  8002. /**
  8003. * Find the next lowest power of two.
  8004. * @param x Number to start search from.
  8005. * @return Next lowest power of two.
  8006. */
  8007. Tools.FloorPOT = function (x) {
  8008. x = x | (x >> 1);
  8009. x = x | (x >> 2);
  8010. x = x | (x >> 4);
  8011. x = x | (x >> 8);
  8012. x = x | (x >> 16);
  8013. return x - (x >> 1);
  8014. };
  8015. /**
  8016. * Find the nearest power of two.
  8017. * @param x Number to start search from.
  8018. * @return Next nearest power of two.
  8019. */
  8020. Tools.NearestPOT = function (x) {
  8021. var c = Tools.CeilingPOT(x);
  8022. var f = Tools.FloorPOT(x);
  8023. return (c - x) > (x - f) ? f : c;
  8024. };
  8025. Tools.GetExponentOfTwo = function (value, max, mode) {
  8026. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8027. var pot;
  8028. switch (mode) {
  8029. case BABYLON.Engine.SCALEMODE_FLOOR:
  8030. pot = Tools.FloorPOT(value);
  8031. break;
  8032. case BABYLON.Engine.SCALEMODE_NEAREST:
  8033. pot = Tools.NearestPOT(value);
  8034. break;
  8035. case BABYLON.Engine.SCALEMODE_CEILING:
  8036. default:
  8037. pot = Tools.CeilingPOT(value);
  8038. break;
  8039. }
  8040. return Math.min(pot, max);
  8041. };
  8042. Tools.GetFilename = function (path) {
  8043. var index = path.lastIndexOf("/");
  8044. if (index < 0)
  8045. return path;
  8046. return path.substring(index + 1);
  8047. };
  8048. /**
  8049. * Extracts the "folder" part of a path (everything before the filename).
  8050. * @param uri The URI to extract the info from
  8051. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8052. * @returns The "folder" part of the path
  8053. */
  8054. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8055. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8056. var index = uri.lastIndexOf("/");
  8057. if (index < 0) {
  8058. if (returnUnchangedIfNoSlash) {
  8059. return uri;
  8060. }
  8061. return "";
  8062. }
  8063. return uri.substring(0, index + 1);
  8064. };
  8065. Tools.GetDOMTextContent = function (element) {
  8066. var result = "";
  8067. var child = element.firstChild;
  8068. while (child) {
  8069. if (child.nodeType === 3) {
  8070. result += child.textContent;
  8071. }
  8072. child = child.nextSibling;
  8073. }
  8074. return result;
  8075. };
  8076. Tools.ToDegrees = function (angle) {
  8077. return angle * 180 / Math.PI;
  8078. };
  8079. Tools.ToRadians = function (angle) {
  8080. return angle * Math.PI / 180;
  8081. };
  8082. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8083. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8084. var output = "";
  8085. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8086. var i = 0;
  8087. var bytes = new Uint8Array(buffer);
  8088. while (i < bytes.length) {
  8089. chr1 = bytes[i++];
  8090. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8091. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8092. enc1 = chr1 >> 2;
  8093. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8094. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8095. enc4 = chr3 & 63;
  8096. if (isNaN(chr2)) {
  8097. enc3 = enc4 = 64;
  8098. }
  8099. else if (isNaN(chr3)) {
  8100. enc4 = 64;
  8101. }
  8102. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8103. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8104. }
  8105. return "data:image/png;base64," + output;
  8106. };
  8107. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8108. if (bias === void 0) { bias = null; }
  8109. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8110. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8111. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8112. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8113. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8114. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8115. }
  8116. if (bias) {
  8117. minimum.x -= minimum.x * bias.x + bias.y;
  8118. minimum.y -= minimum.y * bias.x + bias.y;
  8119. minimum.z -= minimum.z * bias.x + bias.y;
  8120. maximum.x += maximum.x * bias.x + bias.y;
  8121. maximum.y += maximum.y * bias.x + bias.y;
  8122. maximum.z += maximum.z * bias.x + bias.y;
  8123. }
  8124. return {
  8125. minimum: minimum,
  8126. maximum: maximum
  8127. };
  8128. };
  8129. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8130. if (bias === void 0) { bias = null; }
  8131. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8132. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8133. if (!stride) {
  8134. stride = 3;
  8135. }
  8136. for (var index = start; index < start + count; index++) {
  8137. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8138. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8139. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8140. }
  8141. if (bias) {
  8142. minimum.x -= minimum.x * bias.x + bias.y;
  8143. minimum.y -= minimum.y * bias.x + bias.y;
  8144. minimum.z -= minimum.z * bias.x + bias.y;
  8145. maximum.x += maximum.x * bias.x + bias.y;
  8146. maximum.y += maximum.y * bias.x + bias.y;
  8147. maximum.z += maximum.z * bias.x + bias.y;
  8148. }
  8149. return {
  8150. minimum: minimum,
  8151. maximum: maximum
  8152. };
  8153. };
  8154. Tools.Vector2ArrayFeeder = function (array) {
  8155. return function (index) {
  8156. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8157. var length = isFloatArray ? array.length / 2 : array.length;
  8158. if (index >= length) {
  8159. return null;
  8160. }
  8161. if (isFloatArray) {
  8162. var fa = array;
  8163. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8164. }
  8165. var a = array;
  8166. return a[index];
  8167. };
  8168. };
  8169. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8170. if (bias === void 0) { bias = null; }
  8171. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8172. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8173. var i = 0;
  8174. var cur = feeder(i++);
  8175. while (cur) {
  8176. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8177. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8178. cur = feeder(i++);
  8179. }
  8180. if (bias) {
  8181. minimum.x -= minimum.x * bias.x + bias.y;
  8182. minimum.y -= minimum.y * bias.x + bias.y;
  8183. maximum.x += maximum.x * bias.x + bias.y;
  8184. maximum.y += maximum.y * bias.x + bias.y;
  8185. }
  8186. return {
  8187. minimum: minimum,
  8188. maximum: maximum
  8189. };
  8190. };
  8191. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8192. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8193. return null;
  8194. return Array.isArray(obj) ? obj : [obj];
  8195. };
  8196. // Misc.
  8197. Tools.GetPointerPrefix = function () {
  8198. var eventPrefix = "pointer";
  8199. // Check if pointer events are supported
  8200. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8201. eventPrefix = "mouse";
  8202. }
  8203. return eventPrefix;
  8204. };
  8205. /**
  8206. * @param func - the function to be called
  8207. * @param requester - the object that will request the next frame. Falls back to window.
  8208. */
  8209. Tools.QueueNewFrame = function (func, requester) {
  8210. if (!Tools.IsWindowObjectExist()) {
  8211. return setTimeout(func, 16);
  8212. }
  8213. if (!requester) {
  8214. requester = window;
  8215. }
  8216. if (requester.requestAnimationFrame) {
  8217. return requester.requestAnimationFrame(func);
  8218. }
  8219. else if (requester.msRequestAnimationFrame) {
  8220. return requester.msRequestAnimationFrame(func);
  8221. }
  8222. else if (requester.webkitRequestAnimationFrame) {
  8223. return requester.webkitRequestAnimationFrame(func);
  8224. }
  8225. else if (requester.mozRequestAnimationFrame) {
  8226. return requester.mozRequestAnimationFrame(func);
  8227. }
  8228. else if (requester.oRequestAnimationFrame) {
  8229. return requester.oRequestAnimationFrame(func);
  8230. }
  8231. else {
  8232. return window.setTimeout(func, 16);
  8233. }
  8234. };
  8235. Tools.RequestFullscreen = function (element) {
  8236. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8237. if (!requestFunction)
  8238. return;
  8239. requestFunction.call(element);
  8240. };
  8241. Tools.ExitFullscreen = function () {
  8242. if (document.exitFullscreen) {
  8243. document.exitFullscreen();
  8244. }
  8245. else if (document.mozCancelFullScreen) {
  8246. document.mozCancelFullScreen();
  8247. }
  8248. else if (document.webkitCancelFullScreen) {
  8249. document.webkitCancelFullScreen();
  8250. }
  8251. else if (document.msCancelFullScreen) {
  8252. document.msCancelFullScreen();
  8253. }
  8254. };
  8255. Tools.SetCorsBehavior = function (url, element) {
  8256. if (url && url.indexOf("data:") === 0) {
  8257. return;
  8258. }
  8259. if (Tools.CorsBehavior) {
  8260. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8261. element.crossOrigin = Tools.CorsBehavior;
  8262. }
  8263. else {
  8264. var result = Tools.CorsBehavior(url);
  8265. if (result) {
  8266. element.crossOrigin = result;
  8267. }
  8268. }
  8269. }
  8270. };
  8271. // External files
  8272. Tools.CleanUrl = function (url) {
  8273. url = url.replace(/#/mg, "%23");
  8274. return url;
  8275. };
  8276. Tools.LoadImage = function (url, onLoad, onError, database) {
  8277. if (url instanceof ArrayBuffer) {
  8278. url = Tools.EncodeArrayBufferTobase64(url);
  8279. }
  8280. url = Tools.CleanUrl(url);
  8281. url = Tools.PreprocessUrl(url);
  8282. var img = new Image();
  8283. Tools.SetCorsBehavior(url, img);
  8284. var loadHandler = function () {
  8285. img.removeEventListener("load", loadHandler);
  8286. img.removeEventListener("error", errorHandler);
  8287. onLoad(img);
  8288. };
  8289. var errorHandler = function (err) {
  8290. img.removeEventListener("load", loadHandler);
  8291. img.removeEventListener("error", errorHandler);
  8292. Tools.Error("Error while trying to load image: " + url);
  8293. if (onError) {
  8294. onError("Error while trying to load image: " + url, err);
  8295. }
  8296. };
  8297. img.addEventListener("load", loadHandler);
  8298. img.addEventListener("error", errorHandler);
  8299. var noIndexedDB = function () {
  8300. img.src = url;
  8301. };
  8302. var loadFromIndexedDB = function () {
  8303. if (database) {
  8304. database.loadImageFromDB(url, img);
  8305. }
  8306. };
  8307. //ANY database to do!
  8308. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8309. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8310. }
  8311. else {
  8312. if (url.indexOf("file:") !== -1) {
  8313. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8314. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8315. try {
  8316. var blobURL;
  8317. try {
  8318. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8319. }
  8320. catch (ex) {
  8321. // Chrome doesn't support oneTimeOnly parameter
  8322. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8323. }
  8324. img.src = blobURL;
  8325. }
  8326. catch (e) {
  8327. img.src = "";
  8328. }
  8329. return img;
  8330. }
  8331. }
  8332. noIndexedDB();
  8333. }
  8334. return img;
  8335. };
  8336. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8337. url = Tools.CleanUrl(url);
  8338. url = Tools.PreprocessUrl(url);
  8339. // If file and file input are set
  8340. if (url.indexOf("file:") !== -1) {
  8341. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8342. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8343. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8344. }
  8345. }
  8346. var loadUrl = Tools.BaseUrl + url;
  8347. var aborted = false;
  8348. var fileRequest = {
  8349. onCompleteObservable: new BABYLON.Observable(),
  8350. abort: function () { return aborted = true; },
  8351. };
  8352. var requestFile = function () {
  8353. var request = new XMLHttpRequest();
  8354. var retryHandle = null;
  8355. fileRequest.abort = function () {
  8356. aborted = true;
  8357. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8358. request.abort();
  8359. }
  8360. if (retryHandle !== null) {
  8361. clearTimeout(retryHandle);
  8362. retryHandle = null;
  8363. }
  8364. };
  8365. var retryLoop = function (retryIndex) {
  8366. request.open('GET', loadUrl, true);
  8367. if (useArrayBuffer) {
  8368. request.responseType = "arraybuffer";
  8369. }
  8370. if (onProgress) {
  8371. request.addEventListener("progress", onProgress);
  8372. }
  8373. var onLoadEnd = function () {
  8374. request.removeEventListener("loadend", onLoadEnd);
  8375. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8376. fileRequest.onCompleteObservable.clear();
  8377. };
  8378. request.addEventListener("loadend", onLoadEnd);
  8379. var onReadyStateChange = function () {
  8380. if (aborted) {
  8381. return;
  8382. }
  8383. // In case of undefined state in some browsers.
  8384. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8385. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8386. request.removeEventListener("readystatechange", onReadyStateChange);
  8387. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8388. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8389. return;
  8390. }
  8391. var retryStrategy = Tools.DefaultRetryStrategy;
  8392. if (retryStrategy) {
  8393. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8394. if (waitTime !== -1) {
  8395. // Prevent the request from completing for retry.
  8396. request.removeEventListener("loadend", onLoadEnd);
  8397. request = new XMLHttpRequest();
  8398. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8399. return;
  8400. }
  8401. }
  8402. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8403. if (onError) {
  8404. onError(request, e);
  8405. }
  8406. else {
  8407. throw e;
  8408. }
  8409. }
  8410. };
  8411. request.addEventListener("readystatechange", onReadyStateChange);
  8412. request.send();
  8413. };
  8414. retryLoop(0);
  8415. };
  8416. // Caching all files
  8417. if (database && database.enableSceneOffline) {
  8418. var noIndexedDB_1 = function () {
  8419. if (!aborted) {
  8420. requestFile();
  8421. }
  8422. };
  8423. var loadFromIndexedDB = function () {
  8424. // TODO: database needs to support aborting and should return a IFileRequest
  8425. if (aborted) {
  8426. return;
  8427. }
  8428. if (database) {
  8429. database.loadFileFromDB(url, function (data) {
  8430. if (!aborted) {
  8431. onSuccess(data);
  8432. }
  8433. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8434. }, onProgress ? function (event) {
  8435. if (!aborted) {
  8436. onProgress(event);
  8437. }
  8438. } : undefined, noIndexedDB_1, useArrayBuffer);
  8439. }
  8440. };
  8441. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8442. }
  8443. else {
  8444. requestFile();
  8445. }
  8446. return fileRequest;
  8447. };
  8448. /**
  8449. * Load a script (identified by an url). When the url returns, the
  8450. * content of this file is added into a new script element, attached to the DOM (body element)
  8451. */
  8452. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8453. var head = document.getElementsByTagName('head')[0];
  8454. var script = document.createElement('script');
  8455. script.type = 'text/javascript';
  8456. script.src = scriptUrl;
  8457. script.onload = function () {
  8458. if (onSuccess) {
  8459. onSuccess();
  8460. }
  8461. };
  8462. script.onerror = function (e) {
  8463. if (onError) {
  8464. onError("Unable to load script", e);
  8465. }
  8466. };
  8467. head.appendChild(script);
  8468. };
  8469. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8470. var reader = new FileReader();
  8471. var request = {
  8472. onCompleteObservable: new BABYLON.Observable(),
  8473. abort: function () { return reader.abort(); },
  8474. };
  8475. reader.onloadend = function (e) {
  8476. request.onCompleteObservable.notifyObservers(request);
  8477. };
  8478. reader.onload = function (e) {
  8479. //target doesn't have result from ts 1.3
  8480. callback(e.target['result']);
  8481. };
  8482. reader.onprogress = progressCallback;
  8483. reader.readAsDataURL(fileToLoad);
  8484. return request;
  8485. };
  8486. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8487. var reader = new FileReader();
  8488. var request = {
  8489. onCompleteObservable: new BABYLON.Observable(),
  8490. abort: function () { return reader.abort(); },
  8491. };
  8492. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8493. reader.onerror = function (e) {
  8494. Tools.Log("Error while reading file: " + fileToLoad.name);
  8495. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8496. };
  8497. reader.onload = function (e) {
  8498. //target doesn't have result from ts 1.3
  8499. callback(e.target['result']);
  8500. };
  8501. if (progressCallBack) {
  8502. reader.onprogress = progressCallBack;
  8503. }
  8504. if (!useArrayBuffer) {
  8505. // Asynchronous read
  8506. reader.readAsText(fileToLoad);
  8507. }
  8508. else {
  8509. reader.readAsArrayBuffer(fileToLoad);
  8510. }
  8511. return request;
  8512. };
  8513. //returns a downloadable url to a file content.
  8514. Tools.FileAsURL = function (content) {
  8515. var fileBlob = new Blob([content]);
  8516. var url = window.URL || window.webkitURL;
  8517. var link = url.createObjectURL(fileBlob);
  8518. return link;
  8519. };
  8520. // Misc.
  8521. Tools.Format = function (value, decimals) {
  8522. if (decimals === void 0) { decimals = 2; }
  8523. return value.toFixed(decimals);
  8524. };
  8525. Tools.CheckExtends = function (v, min, max) {
  8526. if (v.x < min.x)
  8527. min.x = v.x;
  8528. if (v.y < min.y)
  8529. min.y = v.y;
  8530. if (v.z < min.z)
  8531. min.z = v.z;
  8532. if (v.x > max.x)
  8533. max.x = v.x;
  8534. if (v.y > max.y)
  8535. max.y = v.y;
  8536. if (v.z > max.z)
  8537. max.z = v.z;
  8538. };
  8539. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8540. for (var prop in source) {
  8541. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8542. continue;
  8543. }
  8544. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8545. continue;
  8546. }
  8547. var sourceValue = source[prop];
  8548. var typeOfSourceValue = typeof sourceValue;
  8549. if (typeOfSourceValue === "function") {
  8550. continue;
  8551. }
  8552. try {
  8553. if (typeOfSourceValue === "object") {
  8554. if (sourceValue instanceof Array) {
  8555. destination[prop] = [];
  8556. if (sourceValue.length > 0) {
  8557. if (typeof sourceValue[0] == "object") {
  8558. for (var index = 0; index < sourceValue.length; index++) {
  8559. var clonedValue = cloneValue(sourceValue[index], destination);
  8560. if (destination[prop].indexOf(clonedValue) === -1) {
  8561. destination[prop].push(clonedValue);
  8562. }
  8563. }
  8564. }
  8565. else {
  8566. destination[prop] = sourceValue.slice(0);
  8567. }
  8568. }
  8569. }
  8570. else {
  8571. destination[prop] = cloneValue(sourceValue, destination);
  8572. }
  8573. }
  8574. else {
  8575. destination[prop] = sourceValue;
  8576. }
  8577. }
  8578. catch (e) {
  8579. // Just ignore error (it could be because of a read-only property)
  8580. }
  8581. }
  8582. };
  8583. Tools.IsEmpty = function (obj) {
  8584. for (var i in obj) {
  8585. if (obj.hasOwnProperty(i)) {
  8586. return false;
  8587. }
  8588. }
  8589. return true;
  8590. };
  8591. Tools.RegisterTopRootEvents = function (events) {
  8592. for (var index = 0; index < events.length; index++) {
  8593. var event = events[index];
  8594. window.addEventListener(event.name, event.handler, false);
  8595. try {
  8596. if (window.parent) {
  8597. window.parent.addEventListener(event.name, event.handler, false);
  8598. }
  8599. }
  8600. catch (e) {
  8601. // Silently fails...
  8602. }
  8603. }
  8604. };
  8605. Tools.UnregisterTopRootEvents = function (events) {
  8606. for (var index = 0; index < events.length; index++) {
  8607. var event = events[index];
  8608. window.removeEventListener(event.name, event.handler);
  8609. try {
  8610. if (window.parent) {
  8611. window.parent.removeEventListener(event.name, event.handler);
  8612. }
  8613. }
  8614. catch (e) {
  8615. // Silently fails...
  8616. }
  8617. }
  8618. };
  8619. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8620. if (mimeType === void 0) { mimeType = "image/png"; }
  8621. // Read the contents of the framebuffer
  8622. var numberOfChannelsByLine = width * 4;
  8623. var halfHeight = height / 2;
  8624. //Reading datas from WebGL
  8625. var data = engine.readPixels(0, 0, width, height);
  8626. //To flip image on Y axis.
  8627. for (var i = 0; i < halfHeight; i++) {
  8628. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8629. var currentCell = j + i * numberOfChannelsByLine;
  8630. var targetLine = height - i - 1;
  8631. var targetCell = j + targetLine * numberOfChannelsByLine;
  8632. var temp = data[currentCell];
  8633. data[currentCell] = data[targetCell];
  8634. data[targetCell] = temp;
  8635. }
  8636. }
  8637. // Create a 2D canvas to store the result
  8638. if (!screenshotCanvas) {
  8639. screenshotCanvas = document.createElement('canvas');
  8640. }
  8641. screenshotCanvas.width = width;
  8642. screenshotCanvas.height = height;
  8643. var context = screenshotCanvas.getContext('2d');
  8644. if (context) {
  8645. // Copy the pixels to a 2D canvas
  8646. var imageData = context.createImageData(width, height);
  8647. var castData = (imageData.data);
  8648. castData.set(data);
  8649. context.putImageData(imageData, 0, 0);
  8650. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8651. }
  8652. };
  8653. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8654. if (mimeType === void 0) { mimeType = "image/png"; }
  8655. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8656. if (successCallback) {
  8657. successCallback(base64Image);
  8658. }
  8659. else {
  8660. // We need HTMLCanvasElement.toBlob for HD screenshots
  8661. if (!screenshotCanvas.toBlob) {
  8662. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8663. screenshotCanvas.toBlob = function (callback, type, quality) {
  8664. var _this = this;
  8665. setTimeout(function () {
  8666. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8667. for (var i = 0; i < len; i++) {
  8668. arr[i] = binStr.charCodeAt(i);
  8669. }
  8670. callback(new Blob([arr], { type: type || 'image/png' }));
  8671. });
  8672. };
  8673. }
  8674. screenshotCanvas.toBlob(function (blob) {
  8675. var url = URL.createObjectURL(blob);
  8676. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8677. if (("download" in document.createElement("a"))) {
  8678. var a = window.document.createElement("a");
  8679. a.href = url;
  8680. if (fileName) {
  8681. a.setAttribute("download", fileName);
  8682. }
  8683. else {
  8684. var date = new Date();
  8685. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8686. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8687. }
  8688. window.document.body.appendChild(a);
  8689. a.addEventListener("click", function () {
  8690. if (a.parentElement) {
  8691. a.parentElement.removeChild(a);
  8692. }
  8693. });
  8694. a.click();
  8695. }
  8696. else {
  8697. var newWindow = window.open("");
  8698. if (!newWindow)
  8699. return;
  8700. var img = newWindow.document.createElement("img");
  8701. img.onload = function () {
  8702. // no longer need to read the blob so it's revoked
  8703. URL.revokeObjectURL(url);
  8704. };
  8705. img.src = url;
  8706. newWindow.document.body.appendChild(img);
  8707. }
  8708. });
  8709. }
  8710. };
  8711. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8712. if (mimeType === void 0) { mimeType = "image/png"; }
  8713. var width;
  8714. var height;
  8715. // If a precision value is specified
  8716. if (size.precision) {
  8717. width = Math.round(engine.getRenderWidth() * size.precision);
  8718. height = Math.round(width / engine.getAspectRatio(camera));
  8719. }
  8720. else if (size.width && size.height) {
  8721. width = size.width;
  8722. height = size.height;
  8723. }
  8724. else if (size.width && !size.height) {
  8725. width = size.width;
  8726. height = Math.round(width / engine.getAspectRatio(camera));
  8727. }
  8728. else if (size.height && !size.width) {
  8729. height = size.height;
  8730. width = Math.round(height * engine.getAspectRatio(camera));
  8731. }
  8732. else if (!isNaN(size)) {
  8733. height = size;
  8734. width = size;
  8735. }
  8736. else {
  8737. Tools.Error("Invalid 'size' parameter !");
  8738. return;
  8739. }
  8740. if (!screenshotCanvas) {
  8741. screenshotCanvas = document.createElement('canvas');
  8742. }
  8743. screenshotCanvas.width = width;
  8744. screenshotCanvas.height = height;
  8745. var renderContext = screenshotCanvas.getContext("2d");
  8746. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8747. var newWidth = width;
  8748. var newHeight = newWidth / ratio;
  8749. if (newHeight > height) {
  8750. newHeight = height;
  8751. newWidth = newHeight * ratio;
  8752. }
  8753. var offsetX = Math.max(0, width - newWidth) / 2;
  8754. var offsetY = Math.max(0, height - newHeight) / 2;
  8755. var renderingCanvas = engine.getRenderingCanvas();
  8756. if (renderContext && renderingCanvas) {
  8757. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8758. }
  8759. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8760. };
  8761. /**
  8762. * Generates an image screenshot from the specified camera.
  8763. *
  8764. * @param engine The engine to use for rendering
  8765. * @param camera The camera to use for rendering
  8766. * @param size This parameter can be set to a single number or to an object with the
  8767. * following (optional) properties: precision, width, height. If a single number is passed,
  8768. * it will be used for both width and height. If an object is passed, the screenshot size
  8769. * will be derived from the parameters. The precision property is a multiplier allowing
  8770. * rendering at a higher or lower resolution.
  8771. * @param successCallback The callback receives a single parameter which contains the
  8772. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8773. * src parameter of an <img> to display it.
  8774. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8775. * Check your browser for supported MIME types.
  8776. * @param samples Texture samples (default: 1)
  8777. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8778. * @param fileName A name for for the downloaded file.
  8779. * @constructor
  8780. */
  8781. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8782. if (mimeType === void 0) { mimeType = "image/png"; }
  8783. if (samples === void 0) { samples = 1; }
  8784. if (antialiasing === void 0) { antialiasing = false; }
  8785. var width;
  8786. var height;
  8787. //If a precision value is specified
  8788. if (size.precision) {
  8789. width = Math.round(engine.getRenderWidth() * size.precision);
  8790. height = Math.round(width / engine.getAspectRatio(camera));
  8791. size = { width: width, height: height };
  8792. }
  8793. else if (size.width && size.height) {
  8794. width = size.width;
  8795. height = size.height;
  8796. }
  8797. else if (size.width && !size.height) {
  8798. width = size.width;
  8799. height = Math.round(width / engine.getAspectRatio(camera));
  8800. size = { width: width, height: height };
  8801. }
  8802. else if (size.height && !size.width) {
  8803. height = size.height;
  8804. width = Math.round(height * engine.getAspectRatio(camera));
  8805. size = { width: width, height: height };
  8806. }
  8807. else if (!isNaN(size)) {
  8808. height = size;
  8809. width = size;
  8810. }
  8811. else {
  8812. Tools.Error("Invalid 'size' parameter !");
  8813. return;
  8814. }
  8815. var scene = camera.getScene();
  8816. var previousCamera = null;
  8817. if (scene.activeCamera !== camera) {
  8818. previousCamera = scene.activeCamera;
  8819. scene.activeCamera = camera;
  8820. }
  8821. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8822. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8823. texture.renderList = null;
  8824. texture.samples = samples;
  8825. if (antialiasing) {
  8826. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8827. }
  8828. texture.onAfterRenderObservable.add(function () {
  8829. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8830. });
  8831. scene.incrementRenderId();
  8832. scene.resetCachedMaterial();
  8833. texture.render(true);
  8834. texture.dispose();
  8835. if (previousCamera) {
  8836. scene.activeCamera = previousCamera;
  8837. }
  8838. camera.getProjectionMatrix(true); // Force cache refresh;
  8839. };
  8840. // XHR response validator for local file scenario
  8841. Tools.ValidateXHRData = function (xhr, dataType) {
  8842. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8843. if (dataType === void 0) { dataType = 7; }
  8844. try {
  8845. if (dataType & 1) {
  8846. if (xhr.responseText && xhr.responseText.length > 0) {
  8847. return true;
  8848. }
  8849. else if (dataType === 1) {
  8850. return false;
  8851. }
  8852. }
  8853. if (dataType & 2) {
  8854. // Check header width and height since there is no "TGA" magic number
  8855. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8856. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8857. return true;
  8858. }
  8859. else if (dataType === 2) {
  8860. return false;
  8861. }
  8862. }
  8863. if (dataType & 4) {
  8864. // Check for the "DDS" magic number
  8865. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8866. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8867. return true;
  8868. }
  8869. else {
  8870. return false;
  8871. }
  8872. }
  8873. }
  8874. catch (e) {
  8875. // Global protection
  8876. }
  8877. return false;
  8878. };
  8879. /**
  8880. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8881. * Be aware Math.random() could cause collisions, but:
  8882. * "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"
  8883. */
  8884. Tools.RandomId = function () {
  8885. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8886. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8887. return v.toString(16);
  8888. });
  8889. };
  8890. /**
  8891. * Test if the given uri is a base64 string.
  8892. * @param uri The uri to test
  8893. * @return True if the uri is a base64 string or false otherwise.
  8894. */
  8895. Tools.IsBase64 = function (uri) {
  8896. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8897. };
  8898. /**
  8899. * Decode the given base64 uri.
  8900. * @param uri The uri to decode
  8901. * @return The decoded base64 data.
  8902. */
  8903. Tools.DecodeBase64 = function (uri) {
  8904. var decodedString = atob(uri.split(",")[1]);
  8905. var bufferLength = decodedString.length;
  8906. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8907. for (var i = 0; i < bufferLength; i++) {
  8908. bufferView[i] = decodedString.charCodeAt(i);
  8909. }
  8910. return bufferView.buffer;
  8911. };
  8912. Object.defineProperty(Tools, "NoneLogLevel", {
  8913. get: function () {
  8914. return Tools._NoneLogLevel;
  8915. },
  8916. enumerable: true,
  8917. configurable: true
  8918. });
  8919. Object.defineProperty(Tools, "MessageLogLevel", {
  8920. get: function () {
  8921. return Tools._MessageLogLevel;
  8922. },
  8923. enumerable: true,
  8924. configurable: true
  8925. });
  8926. Object.defineProperty(Tools, "WarningLogLevel", {
  8927. get: function () {
  8928. return Tools._WarningLogLevel;
  8929. },
  8930. enumerable: true,
  8931. configurable: true
  8932. });
  8933. Object.defineProperty(Tools, "ErrorLogLevel", {
  8934. get: function () {
  8935. return Tools._ErrorLogLevel;
  8936. },
  8937. enumerable: true,
  8938. configurable: true
  8939. });
  8940. Object.defineProperty(Tools, "AllLogLevel", {
  8941. get: function () {
  8942. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8943. },
  8944. enumerable: true,
  8945. configurable: true
  8946. });
  8947. Tools._AddLogEntry = function (entry) {
  8948. Tools._LogCache = entry + Tools._LogCache;
  8949. if (Tools.OnNewCacheEntry) {
  8950. Tools.OnNewCacheEntry(entry);
  8951. }
  8952. };
  8953. Tools._FormatMessage = function (message) {
  8954. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8955. var date = new Date();
  8956. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8957. };
  8958. Tools._LogDisabled = function (message) {
  8959. // nothing to do
  8960. };
  8961. Tools._LogEnabled = function (message) {
  8962. var formattedMessage = Tools._FormatMessage(message);
  8963. console.log("BJS - " + formattedMessage);
  8964. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8965. Tools._AddLogEntry(entry);
  8966. };
  8967. Tools._WarnDisabled = function (message) {
  8968. // nothing to do
  8969. };
  8970. Tools._WarnEnabled = function (message) {
  8971. var formattedMessage = Tools._FormatMessage(message);
  8972. console.warn("BJS - " + formattedMessage);
  8973. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8974. Tools._AddLogEntry(entry);
  8975. };
  8976. Tools._ErrorDisabled = function (message) {
  8977. // nothing to do
  8978. };
  8979. Tools._ErrorEnabled = function (message) {
  8980. Tools.errorsCount++;
  8981. var formattedMessage = Tools._FormatMessage(message);
  8982. console.error("BJS - " + formattedMessage);
  8983. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  8984. Tools._AddLogEntry(entry);
  8985. };
  8986. Object.defineProperty(Tools, "LogCache", {
  8987. get: function () {
  8988. return Tools._LogCache;
  8989. },
  8990. enumerable: true,
  8991. configurable: true
  8992. });
  8993. Tools.ClearLogCache = function () {
  8994. Tools._LogCache = "";
  8995. Tools.errorsCount = 0;
  8996. };
  8997. Object.defineProperty(Tools, "LogLevels", {
  8998. set: function (level) {
  8999. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9000. Tools.Log = Tools._LogEnabled;
  9001. }
  9002. else {
  9003. Tools.Log = Tools._LogDisabled;
  9004. }
  9005. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9006. Tools.Warn = Tools._WarnEnabled;
  9007. }
  9008. else {
  9009. Tools.Warn = Tools._WarnDisabled;
  9010. }
  9011. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9012. Tools.Error = Tools._ErrorEnabled;
  9013. }
  9014. else {
  9015. Tools.Error = Tools._ErrorDisabled;
  9016. }
  9017. },
  9018. enumerable: true,
  9019. configurable: true
  9020. });
  9021. Tools.IsWindowObjectExist = function () {
  9022. return (typeof window) !== "undefined";
  9023. };
  9024. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9025. get: function () {
  9026. return Tools._PerformanceNoneLogLevel;
  9027. },
  9028. enumerable: true,
  9029. configurable: true
  9030. });
  9031. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9032. get: function () {
  9033. return Tools._PerformanceUserMarkLogLevel;
  9034. },
  9035. enumerable: true,
  9036. configurable: true
  9037. });
  9038. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9039. get: function () {
  9040. return Tools._PerformanceConsoleLogLevel;
  9041. },
  9042. enumerable: true,
  9043. configurable: true
  9044. });
  9045. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9046. set: function (level) {
  9047. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9048. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9049. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9050. return;
  9051. }
  9052. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9053. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9054. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9055. return;
  9056. }
  9057. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9058. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9059. },
  9060. enumerable: true,
  9061. configurable: true
  9062. });
  9063. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9064. };
  9065. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9066. };
  9067. Tools._StartUserMark = function (counterName, condition) {
  9068. if (condition === void 0) { condition = true; }
  9069. if (!Tools._performance) {
  9070. if (!Tools.IsWindowObjectExist()) {
  9071. return;
  9072. }
  9073. Tools._performance = window.performance;
  9074. }
  9075. if (!condition || !Tools._performance.mark) {
  9076. return;
  9077. }
  9078. Tools._performance.mark(counterName + "-Begin");
  9079. };
  9080. Tools._EndUserMark = function (counterName, condition) {
  9081. if (condition === void 0) { condition = true; }
  9082. if (!condition || !Tools._performance.mark) {
  9083. return;
  9084. }
  9085. Tools._performance.mark(counterName + "-End");
  9086. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9087. };
  9088. Tools._StartPerformanceConsole = function (counterName, condition) {
  9089. if (condition === void 0) { condition = true; }
  9090. if (!condition) {
  9091. return;
  9092. }
  9093. Tools._StartUserMark(counterName, condition);
  9094. if (console.time) {
  9095. console.time(counterName);
  9096. }
  9097. };
  9098. Tools._EndPerformanceConsole = function (counterName, condition) {
  9099. if (condition === void 0) { condition = true; }
  9100. if (!condition) {
  9101. return;
  9102. }
  9103. Tools._EndUserMark(counterName, condition);
  9104. if (console.time) {
  9105. console.timeEnd(counterName);
  9106. }
  9107. };
  9108. Object.defineProperty(Tools, "Now", {
  9109. get: function () {
  9110. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9111. return window.performance.now();
  9112. }
  9113. return new Date().getTime();
  9114. },
  9115. enumerable: true,
  9116. configurable: true
  9117. });
  9118. /**
  9119. * This method will return the name of the class used to create the instance of the given object.
  9120. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9121. * @param object the object to get the class name from
  9122. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9123. */
  9124. Tools.GetClassName = function (object, isType) {
  9125. if (isType === void 0) { isType = false; }
  9126. var name = null;
  9127. if (!isType && object.getClassName) {
  9128. name = object.getClassName();
  9129. }
  9130. else {
  9131. if (object instanceof Object) {
  9132. var classObj = isType ? object : Object.getPrototypeOf(object);
  9133. name = classObj.constructor["__bjsclassName__"];
  9134. }
  9135. if (!name) {
  9136. name = typeof object;
  9137. }
  9138. }
  9139. return name;
  9140. };
  9141. Tools.First = function (array, predicate) {
  9142. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9143. var el = array_1[_i];
  9144. if (predicate(el)) {
  9145. return el;
  9146. }
  9147. }
  9148. return null;
  9149. };
  9150. /**
  9151. * This method will return the name of the full name of the class, including its owning module (if any).
  9152. * 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).
  9153. * @param object the object to get the class name from
  9154. * @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.
  9155. */
  9156. Tools.getFullClassName = function (object, isType) {
  9157. if (isType === void 0) { isType = false; }
  9158. var className = null;
  9159. var moduleName = null;
  9160. if (!isType && object.getClassName) {
  9161. className = object.getClassName();
  9162. }
  9163. else {
  9164. if (object instanceof Object) {
  9165. var classObj = isType ? object : Object.getPrototypeOf(object);
  9166. className = classObj.constructor["__bjsclassName__"];
  9167. moduleName = classObj.constructor["__bjsmoduleName__"];
  9168. }
  9169. if (!className) {
  9170. className = typeof object;
  9171. }
  9172. }
  9173. if (!className) {
  9174. return null;
  9175. }
  9176. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9177. };
  9178. /**
  9179. * 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.
  9180. * @param array
  9181. */
  9182. Tools.arrayOrStringFeeder = function (array) {
  9183. return function (index) {
  9184. if (index >= array.length) {
  9185. return null;
  9186. }
  9187. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9188. if (val && val.getHashCode) {
  9189. val = val.getHashCode();
  9190. }
  9191. if (typeof val === "string") {
  9192. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9193. }
  9194. return val;
  9195. };
  9196. };
  9197. /**
  9198. * Compute the hashCode of a stream of number
  9199. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9200. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9201. * @return the hash code computed
  9202. */
  9203. Tools.hashCodeFromStream = function (feeder) {
  9204. // Based from here: http://stackoverflow.com/a/7616484/802124
  9205. var hash = 0;
  9206. var index = 0;
  9207. var chr = feeder(index++);
  9208. while (chr != null) {
  9209. hash = ((hash << 5) - hash) + chr;
  9210. hash |= 0; // Convert to 32bit integer
  9211. chr = feeder(index++);
  9212. }
  9213. return hash;
  9214. };
  9215. /**
  9216. * Returns a promise that resolves after the given amount of time.
  9217. * @param delay Number of milliseconds to delay
  9218. * @returns Promise that resolves after the given amount of time
  9219. */
  9220. Tools.DelayAsync = function (delay) {
  9221. return new Promise(function (resolve) {
  9222. setTimeout(function () {
  9223. resolve();
  9224. }, delay);
  9225. });
  9226. };
  9227. Tools.BaseUrl = "";
  9228. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9229. /**
  9230. * Default behaviour for cors in the application.
  9231. * It can be a string if the expected behavior is identical in the entire app.
  9232. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9233. */
  9234. Tools.CorsBehavior = "anonymous";
  9235. Tools.UseFallbackTexture = true;
  9236. /**
  9237. * Use this object to register external classes like custom textures or material
  9238. * to allow the laoders to instantiate them
  9239. */
  9240. Tools.RegisteredExternalClasses = {};
  9241. // Used in case of a texture loading problem
  9242. 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";
  9243. Tools.PreprocessUrl = function (url) {
  9244. return url;
  9245. };
  9246. // Logs
  9247. Tools._NoneLogLevel = 0;
  9248. Tools._MessageLogLevel = 1;
  9249. Tools._WarningLogLevel = 2;
  9250. Tools._ErrorLogLevel = 4;
  9251. Tools._LogCache = "";
  9252. Tools.errorsCount = 0;
  9253. Tools.Log = Tools._LogEnabled;
  9254. Tools.Warn = Tools._WarnEnabled;
  9255. Tools.Error = Tools._ErrorEnabled;
  9256. // Performances
  9257. Tools._PerformanceNoneLogLevel = 0;
  9258. Tools._PerformanceUserMarkLogLevel = 1;
  9259. Tools._PerformanceConsoleLogLevel = 2;
  9260. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9261. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9262. return Tools;
  9263. }());
  9264. BABYLON.Tools = Tools;
  9265. /**
  9266. * This class is used to track a performance counter which is number based.
  9267. * The user has access to many properties which give statistics of different nature
  9268. *
  9269. * The implementer can track two kinds of Performance Counter: time and count
  9270. * 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.
  9271. * 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.
  9272. */
  9273. var PerfCounter = /** @class */ (function () {
  9274. function PerfCounter() {
  9275. this._startMonitoringTime = 0;
  9276. this._min = 0;
  9277. this._max = 0;
  9278. this._average = 0;
  9279. this._lastSecAverage = 0;
  9280. this._current = 0;
  9281. this._totalValueCount = 0;
  9282. this._totalAccumulated = 0;
  9283. this._lastSecAccumulated = 0;
  9284. this._lastSecTime = 0;
  9285. this._lastSecValueCount = 0;
  9286. }
  9287. Object.defineProperty(PerfCounter.prototype, "min", {
  9288. /**
  9289. * Returns the smallest value ever
  9290. */
  9291. get: function () {
  9292. return this._min;
  9293. },
  9294. enumerable: true,
  9295. configurable: true
  9296. });
  9297. Object.defineProperty(PerfCounter.prototype, "max", {
  9298. /**
  9299. * Returns the biggest value ever
  9300. */
  9301. get: function () {
  9302. return this._max;
  9303. },
  9304. enumerable: true,
  9305. configurable: true
  9306. });
  9307. Object.defineProperty(PerfCounter.prototype, "average", {
  9308. /**
  9309. * Returns the average value since the performance counter is running
  9310. */
  9311. get: function () {
  9312. return this._average;
  9313. },
  9314. enumerable: true,
  9315. configurable: true
  9316. });
  9317. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9318. /**
  9319. * Returns the average value of the last second the counter was monitored
  9320. */
  9321. get: function () {
  9322. return this._lastSecAverage;
  9323. },
  9324. enumerable: true,
  9325. configurable: true
  9326. });
  9327. Object.defineProperty(PerfCounter.prototype, "current", {
  9328. /**
  9329. * Returns the current value
  9330. */
  9331. get: function () {
  9332. return this._current;
  9333. },
  9334. enumerable: true,
  9335. configurable: true
  9336. });
  9337. Object.defineProperty(PerfCounter.prototype, "total", {
  9338. get: function () {
  9339. return this._totalAccumulated;
  9340. },
  9341. enumerable: true,
  9342. configurable: true
  9343. });
  9344. Object.defineProperty(PerfCounter.prototype, "count", {
  9345. get: function () {
  9346. return this._totalValueCount;
  9347. },
  9348. enumerable: true,
  9349. configurable: true
  9350. });
  9351. /**
  9352. * Call this method to start monitoring a new frame.
  9353. * 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.
  9354. */
  9355. PerfCounter.prototype.fetchNewFrame = function () {
  9356. this._totalValueCount++;
  9357. this._current = 0;
  9358. this._lastSecValueCount++;
  9359. };
  9360. /**
  9361. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9362. * @param newCount the count value to add to the monitored count
  9363. * @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.
  9364. */
  9365. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9366. if (!PerfCounter.Enabled) {
  9367. return;
  9368. }
  9369. this._current += newCount;
  9370. if (fetchResult) {
  9371. this._fetchResult();
  9372. }
  9373. };
  9374. /**
  9375. * Start monitoring this performance counter
  9376. */
  9377. PerfCounter.prototype.beginMonitoring = function () {
  9378. if (!PerfCounter.Enabled) {
  9379. return;
  9380. }
  9381. this._startMonitoringTime = Tools.Now;
  9382. };
  9383. /**
  9384. * Compute the time lapsed since the previous beginMonitoring() call.
  9385. * @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
  9386. */
  9387. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9388. if (newFrame === void 0) { newFrame = true; }
  9389. if (!PerfCounter.Enabled) {
  9390. return;
  9391. }
  9392. if (newFrame) {
  9393. this.fetchNewFrame();
  9394. }
  9395. var currentTime = Tools.Now;
  9396. this._current = currentTime - this._startMonitoringTime;
  9397. if (newFrame) {
  9398. this._fetchResult();
  9399. }
  9400. };
  9401. PerfCounter.prototype._fetchResult = function () {
  9402. this._totalAccumulated += this._current;
  9403. this._lastSecAccumulated += this._current;
  9404. // Min/Max update
  9405. this._min = Math.min(this._min, this._current);
  9406. this._max = Math.max(this._max, this._current);
  9407. this._average = this._totalAccumulated / this._totalValueCount;
  9408. // Reset last sec?
  9409. var now = Tools.Now;
  9410. if ((now - this._lastSecTime) > 1000) {
  9411. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9412. this._lastSecTime = now;
  9413. this._lastSecAccumulated = 0;
  9414. this._lastSecValueCount = 0;
  9415. }
  9416. };
  9417. PerfCounter.Enabled = true;
  9418. return PerfCounter;
  9419. }());
  9420. BABYLON.PerfCounter = PerfCounter;
  9421. /**
  9422. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9423. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9424. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9425. * @param name The name of the class, case should be preserved
  9426. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9427. */
  9428. function className(name, module) {
  9429. return function (target) {
  9430. target["__bjsclassName__"] = name;
  9431. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9432. };
  9433. }
  9434. BABYLON.className = className;
  9435. /**
  9436. * An implementation of a loop for asynchronous functions.
  9437. */
  9438. var AsyncLoop = /** @class */ (function () {
  9439. /**
  9440. * Constroctor.
  9441. * @param iterations the number of iterations.
  9442. * @param _fn the function to run each iteration
  9443. * @param _successCallback the callback that will be called upon succesful execution
  9444. * @param offset starting offset.
  9445. */
  9446. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9447. if (offset === void 0) { offset = 0; }
  9448. this.iterations = iterations;
  9449. this._fn = _fn;
  9450. this._successCallback = _successCallback;
  9451. this.index = offset - 1;
  9452. this._done = false;
  9453. }
  9454. /**
  9455. * Execute the next iteration. Must be called after the last iteration was finished.
  9456. */
  9457. AsyncLoop.prototype.executeNext = function () {
  9458. if (!this._done) {
  9459. if (this.index + 1 < this.iterations) {
  9460. ++this.index;
  9461. this._fn(this);
  9462. }
  9463. else {
  9464. this.breakLoop();
  9465. }
  9466. }
  9467. };
  9468. /**
  9469. * Break the loop and run the success callback.
  9470. */
  9471. AsyncLoop.prototype.breakLoop = function () {
  9472. this._done = true;
  9473. this._successCallback();
  9474. };
  9475. /**
  9476. * Helper function
  9477. */
  9478. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9479. if (offset === void 0) { offset = 0; }
  9480. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9481. loop.executeNext();
  9482. return loop;
  9483. };
  9484. /**
  9485. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9486. * @param iterations total number of iterations
  9487. * @param syncedIterations number of synchronous iterations in each async iteration.
  9488. * @param fn the function to call each iteration.
  9489. * @param callback a success call back that will be called when iterating stops.
  9490. * @param breakFunction a break condition (optional)
  9491. * @param timeout timeout settings for the setTimeout function. default - 0.
  9492. * @constructor
  9493. */
  9494. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9495. if (timeout === void 0) { timeout = 0; }
  9496. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9497. if (breakFunction && breakFunction())
  9498. loop.breakLoop();
  9499. else {
  9500. setTimeout(function () {
  9501. for (var i = 0; i < syncedIterations; ++i) {
  9502. var iteration = (loop.index * syncedIterations) + i;
  9503. if (iteration >= iterations)
  9504. break;
  9505. fn(iteration);
  9506. if (breakFunction && breakFunction()) {
  9507. loop.breakLoop();
  9508. break;
  9509. }
  9510. }
  9511. loop.executeNext();
  9512. }, timeout);
  9513. }
  9514. }, callback);
  9515. };
  9516. return AsyncLoop;
  9517. }());
  9518. BABYLON.AsyncLoop = AsyncLoop;
  9519. })(BABYLON || (BABYLON = {}));
  9520. //# sourceMappingURL=babylon.tools.js.map
  9521. "use strict";
  9522. var BABYLON;
  9523. (function (BABYLON) {
  9524. var PromiseStates;
  9525. (function (PromiseStates) {
  9526. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9527. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9528. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9529. })(PromiseStates || (PromiseStates = {}));
  9530. var FulFillmentAgregator = /** @class */ (function () {
  9531. function FulFillmentAgregator() {
  9532. this.count = 0;
  9533. this.target = 0;
  9534. this.results = [];
  9535. }
  9536. return FulFillmentAgregator;
  9537. }());
  9538. var InternalPromise = /** @class */ (function () {
  9539. function InternalPromise(resolver) {
  9540. var _this = this;
  9541. this._state = PromiseStates.Pending;
  9542. this._children = new Array();
  9543. this._rejectWasConsumed = false;
  9544. if (!resolver) {
  9545. return;
  9546. }
  9547. try {
  9548. resolver(function (value) {
  9549. _this._resolve(value);
  9550. }, function (reason) {
  9551. _this._reject(reason);
  9552. });
  9553. }
  9554. catch (e) {
  9555. this._reject(e);
  9556. }
  9557. }
  9558. InternalPromise.prototype.catch = function (onRejected) {
  9559. return this.then(undefined, onRejected);
  9560. };
  9561. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9562. var _this = this;
  9563. var newPromise = new InternalPromise();
  9564. newPromise._onFulfilled = onFulfilled;
  9565. newPromise._onRejected = onRejected;
  9566. // Composition
  9567. this._children.push(newPromise);
  9568. if (this._state !== PromiseStates.Pending) {
  9569. BABYLON.Tools.SetImmediate(function () {
  9570. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9571. var returnedValue = newPromise._resolve(_this._result);
  9572. if (returnedValue !== undefined && returnedValue !== null) {
  9573. if (returnedValue._state !== undefined) {
  9574. var returnedPromise = returnedValue;
  9575. newPromise._children.push(returnedPromise);
  9576. newPromise = returnedPromise;
  9577. }
  9578. else {
  9579. newPromise._result = returnedValue;
  9580. }
  9581. }
  9582. }
  9583. else {
  9584. newPromise._reject(_this._reason);
  9585. }
  9586. });
  9587. }
  9588. return newPromise;
  9589. };
  9590. InternalPromise.prototype._moveChildren = function (children) {
  9591. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9592. if (this._state === PromiseStates.Fulfilled) {
  9593. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9594. var child = _b[_i];
  9595. child._resolve(this._result);
  9596. }
  9597. }
  9598. else if (this._state === PromiseStates.Rejected) {
  9599. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9600. var child = _d[_c];
  9601. child._reject(this._reason);
  9602. }
  9603. }
  9604. var _a;
  9605. };
  9606. InternalPromise.prototype._resolve = function (value) {
  9607. try {
  9608. this._state = PromiseStates.Fulfilled;
  9609. var returnedValue = null;
  9610. if (this._onFulfilled) {
  9611. returnedValue = this._onFulfilled(value);
  9612. }
  9613. if (returnedValue !== undefined && returnedValue !== null) {
  9614. if (returnedValue._state !== undefined) {
  9615. // Transmit children
  9616. var returnedPromise = returnedValue;
  9617. returnedPromise._moveChildren(this._children);
  9618. value = returnedPromise._result;
  9619. }
  9620. else {
  9621. value = returnedValue;
  9622. }
  9623. }
  9624. this._result = value;
  9625. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9626. var child = _a[_i];
  9627. child._resolve(value);
  9628. }
  9629. this._children.length = 0;
  9630. delete this._onFulfilled;
  9631. delete this._onRejected;
  9632. }
  9633. catch (e) {
  9634. this._reject(e, true);
  9635. }
  9636. };
  9637. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9638. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9639. this._state = PromiseStates.Rejected;
  9640. this._reason = reason;
  9641. if (this._onRejected && !onLocalThrow) {
  9642. try {
  9643. this._onRejected(reason);
  9644. this._rejectWasConsumed = true;
  9645. }
  9646. catch (e) {
  9647. reason = e;
  9648. }
  9649. }
  9650. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9651. var child = _a[_i];
  9652. if (this._rejectWasConsumed) {
  9653. child._resolve(null);
  9654. }
  9655. else {
  9656. child._reject(reason);
  9657. }
  9658. }
  9659. this._children.length = 0;
  9660. delete this._onFulfilled;
  9661. delete this._onRejected;
  9662. };
  9663. InternalPromise.resolve = function (value) {
  9664. var newPromise = new InternalPromise();
  9665. newPromise._resolve(value);
  9666. return newPromise;
  9667. };
  9668. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9669. promise.then(function (value) {
  9670. agregator.results[index] = value;
  9671. agregator.count++;
  9672. if (agregator.count === agregator.target) {
  9673. agregator.rootPromise._resolve(agregator.results);
  9674. }
  9675. return null;
  9676. }, function (reason) {
  9677. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9678. agregator.rootPromise._reject(reason);
  9679. }
  9680. });
  9681. };
  9682. InternalPromise.all = function (promises) {
  9683. var newPromise = new InternalPromise();
  9684. var agregator = new FulFillmentAgregator();
  9685. agregator.target = promises.length;
  9686. agregator.rootPromise = newPromise;
  9687. if (promises.length) {
  9688. for (var index = 0; index < promises.length; index++) {
  9689. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9690. }
  9691. }
  9692. else {
  9693. newPromise._resolve([]);
  9694. }
  9695. return newPromise;
  9696. };
  9697. InternalPromise.race = function (promises) {
  9698. var newPromise = new InternalPromise();
  9699. if (promises.length) {
  9700. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  9701. var promise = promises_1[_i];
  9702. promise.then(function (value) {
  9703. if (newPromise) {
  9704. newPromise._resolve(value);
  9705. newPromise = null;
  9706. }
  9707. return null;
  9708. }, function (reason) {
  9709. if (newPromise) {
  9710. newPromise._reject(reason);
  9711. newPromise = null;
  9712. }
  9713. });
  9714. }
  9715. }
  9716. return newPromise;
  9717. };
  9718. return InternalPromise;
  9719. }());
  9720. /**
  9721. * Helper class that provides a small promise polyfill
  9722. */
  9723. var PromisePolyfill = /** @class */ (function () {
  9724. function PromisePolyfill() {
  9725. }
  9726. /**
  9727. * Static function used to check if the polyfill is required
  9728. * If this is the case then the function will inject the polyfill to window.Promise
  9729. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9730. */
  9731. PromisePolyfill.Apply = function (force) {
  9732. if (force === void 0) { force = false; }
  9733. if (force || typeof Promise === 'undefined') {
  9734. var root = window;
  9735. root.Promise = InternalPromise;
  9736. }
  9737. };
  9738. return PromisePolyfill;
  9739. }());
  9740. BABYLON.PromisePolyfill = PromisePolyfill;
  9741. })(BABYLON || (BABYLON = {}));
  9742. //# sourceMappingURL=babylon.promise.js.map
  9743. "use strict";
  9744. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  9745. var BABYLON;
  9746. (function (BABYLON) {
  9747. /**
  9748. * Helper class to push actions to a pool of workers.
  9749. */
  9750. var WorkerPool = /** @class */ (function () {
  9751. /**
  9752. * Constructor
  9753. * @param workers Array of workers to use for actions
  9754. */
  9755. function WorkerPool(workers) {
  9756. this._pendingActions = new Array();
  9757. this._workerInfos = workers.map(function (worker) { return ({
  9758. worker: worker,
  9759. active: false
  9760. }); });
  9761. }
  9762. /**
  9763. * Terminates all workers and clears any pending actions.
  9764. */
  9765. WorkerPool.prototype.dispose = function () {
  9766. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9767. var workerInfo = _a[_i];
  9768. workerInfo.worker.terminate();
  9769. }
  9770. delete this._workerInfos;
  9771. delete this._pendingActions;
  9772. };
  9773. /**
  9774. * Pushes an action to the worker pool. If all the workers are active, the action will be
  9775. * pended until a worker has completed its action.
  9776. * @param action The action to perform. Call onComplete when the action is complete.
  9777. */
  9778. WorkerPool.prototype.push = function (action) {
  9779. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9780. var workerInfo = _a[_i];
  9781. if (!workerInfo.active) {
  9782. this._execute(workerInfo, action);
  9783. return;
  9784. }
  9785. }
  9786. this._pendingActions.push(action);
  9787. };
  9788. WorkerPool.prototype._execute = function (workerInfo, action) {
  9789. var _this = this;
  9790. workerInfo.active = true;
  9791. action(workerInfo.worker, function () {
  9792. workerInfo.active = false;
  9793. var nextAction = _this._pendingActions.shift();
  9794. if (nextAction) {
  9795. _this._execute(workerInfo, nextAction);
  9796. }
  9797. });
  9798. };
  9799. return WorkerPool;
  9800. }());
  9801. BABYLON.WorkerPool = WorkerPool;
  9802. })(BABYLON || (BABYLON = {}));
  9803. //# sourceMappingURL=babylon.workerPool.js.map
  9804. "use strict";
  9805. var BABYLON;
  9806. (function (BABYLON) {
  9807. var _AlphaState = /** @class */ (function () {
  9808. /**
  9809. * Initializes the state.
  9810. */
  9811. function _AlphaState() {
  9812. this._isAlphaBlendDirty = false;
  9813. this._isBlendFunctionParametersDirty = false;
  9814. this._isBlendEquationParametersDirty = false;
  9815. this._isBlendConstantsDirty = false;
  9816. this._alphaBlend = false;
  9817. this._blendFunctionParameters = new Array(4);
  9818. this._blendEquationParameters = new Array(2);
  9819. this._blendConstants = new Array(4);
  9820. this.reset();
  9821. }
  9822. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9823. get: function () {
  9824. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9825. },
  9826. enumerable: true,
  9827. configurable: true
  9828. });
  9829. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9830. get: function () {
  9831. return this._alphaBlend;
  9832. },
  9833. set: function (value) {
  9834. if (this._alphaBlend === value) {
  9835. return;
  9836. }
  9837. this._alphaBlend = value;
  9838. this._isAlphaBlendDirty = true;
  9839. },
  9840. enumerable: true,
  9841. configurable: true
  9842. });
  9843. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9844. if (this._blendConstants[0] === r &&
  9845. this._blendConstants[1] === g &&
  9846. this._blendConstants[2] === b &&
  9847. this._blendConstants[3] === a) {
  9848. return;
  9849. }
  9850. this._blendConstants[0] = r;
  9851. this._blendConstants[1] = g;
  9852. this._blendConstants[2] = b;
  9853. this._blendConstants[3] = a;
  9854. this._isBlendConstantsDirty = true;
  9855. };
  9856. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9857. if (this._blendFunctionParameters[0] === value0 &&
  9858. this._blendFunctionParameters[1] === value1 &&
  9859. this._blendFunctionParameters[2] === value2 &&
  9860. this._blendFunctionParameters[3] === value3) {
  9861. return;
  9862. }
  9863. this._blendFunctionParameters[0] = value0;
  9864. this._blendFunctionParameters[1] = value1;
  9865. this._blendFunctionParameters[2] = value2;
  9866. this._blendFunctionParameters[3] = value3;
  9867. this._isBlendFunctionParametersDirty = true;
  9868. };
  9869. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9870. if (this._blendEquationParameters[0] === rgb &&
  9871. this._blendEquationParameters[1] === alpha) {
  9872. return;
  9873. }
  9874. this._blendEquationParameters[0] = rgb;
  9875. this._blendEquationParameters[1] = alpha;
  9876. this._isBlendEquationParametersDirty = true;
  9877. };
  9878. _AlphaState.prototype.reset = function () {
  9879. this._alphaBlend = false;
  9880. this._blendFunctionParameters[0] = null;
  9881. this._blendFunctionParameters[1] = null;
  9882. this._blendFunctionParameters[2] = null;
  9883. this._blendFunctionParameters[3] = null;
  9884. this._blendEquationParameters[0] = null;
  9885. this._blendEquationParameters[1] = null;
  9886. this._blendConstants[0] = null;
  9887. this._blendConstants[1] = null;
  9888. this._blendConstants[2] = null;
  9889. this._blendConstants[3] = null;
  9890. this._isAlphaBlendDirty = true;
  9891. this._isBlendFunctionParametersDirty = false;
  9892. this._isBlendEquationParametersDirty = false;
  9893. this._isBlendConstantsDirty = false;
  9894. };
  9895. _AlphaState.prototype.apply = function (gl) {
  9896. if (!this.isDirty) {
  9897. return;
  9898. }
  9899. // Alpha blend
  9900. if (this._isAlphaBlendDirty) {
  9901. if (this._alphaBlend) {
  9902. gl.enable(gl.BLEND);
  9903. }
  9904. else {
  9905. gl.disable(gl.BLEND);
  9906. }
  9907. this._isAlphaBlendDirty = false;
  9908. }
  9909. // Alpha function
  9910. if (this._isBlendFunctionParametersDirty) {
  9911. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9912. this._isBlendFunctionParametersDirty = false;
  9913. }
  9914. // Alpha equation
  9915. if (this._isBlendEquationParametersDirty) {
  9916. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9917. this._isBlendEquationParametersDirty = false;
  9918. }
  9919. // Constants
  9920. if (this._isBlendConstantsDirty) {
  9921. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9922. this._isBlendConstantsDirty = false;
  9923. }
  9924. };
  9925. return _AlphaState;
  9926. }());
  9927. BABYLON._AlphaState = _AlphaState;
  9928. })(BABYLON || (BABYLON = {}));
  9929. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9930. "use strict";
  9931. var BABYLON;
  9932. (function (BABYLON) {
  9933. var _DepthCullingState = /** @class */ (function () {
  9934. /**
  9935. * Initializes the state.
  9936. */
  9937. function _DepthCullingState() {
  9938. this._isDepthTestDirty = false;
  9939. this._isDepthMaskDirty = false;
  9940. this._isDepthFuncDirty = false;
  9941. this._isCullFaceDirty = false;
  9942. this._isCullDirty = false;
  9943. this._isZOffsetDirty = false;
  9944. this._isFrontFaceDirty = false;
  9945. this.reset();
  9946. }
  9947. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9948. get: function () {
  9949. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  9950. },
  9951. enumerable: true,
  9952. configurable: true
  9953. });
  9954. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  9955. get: function () {
  9956. return this._zOffset;
  9957. },
  9958. set: function (value) {
  9959. if (this._zOffset === value) {
  9960. return;
  9961. }
  9962. this._zOffset = value;
  9963. this._isZOffsetDirty = true;
  9964. },
  9965. enumerable: true,
  9966. configurable: true
  9967. });
  9968. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  9969. get: function () {
  9970. return this._cullFace;
  9971. },
  9972. set: function (value) {
  9973. if (this._cullFace === value) {
  9974. return;
  9975. }
  9976. this._cullFace = value;
  9977. this._isCullFaceDirty = true;
  9978. },
  9979. enumerable: true,
  9980. configurable: true
  9981. });
  9982. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  9983. get: function () {
  9984. return this._cull;
  9985. },
  9986. set: function (value) {
  9987. if (this._cull === value) {
  9988. return;
  9989. }
  9990. this._cull = value;
  9991. this._isCullDirty = true;
  9992. },
  9993. enumerable: true,
  9994. configurable: true
  9995. });
  9996. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  9997. get: function () {
  9998. return this._depthFunc;
  9999. },
  10000. set: function (value) {
  10001. if (this._depthFunc === value) {
  10002. return;
  10003. }
  10004. this._depthFunc = value;
  10005. this._isDepthFuncDirty = true;
  10006. },
  10007. enumerable: true,
  10008. configurable: true
  10009. });
  10010. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10011. get: function () {
  10012. return this._depthMask;
  10013. },
  10014. set: function (value) {
  10015. if (this._depthMask === value) {
  10016. return;
  10017. }
  10018. this._depthMask = value;
  10019. this._isDepthMaskDirty = true;
  10020. },
  10021. enumerable: true,
  10022. configurable: true
  10023. });
  10024. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10025. get: function () {
  10026. return this._depthTest;
  10027. },
  10028. set: function (value) {
  10029. if (this._depthTest === value) {
  10030. return;
  10031. }
  10032. this._depthTest = value;
  10033. this._isDepthTestDirty = true;
  10034. },
  10035. enumerable: true,
  10036. configurable: true
  10037. });
  10038. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10039. get: function () {
  10040. return this._frontFace;
  10041. },
  10042. set: function (value) {
  10043. if (this._frontFace === value) {
  10044. return;
  10045. }
  10046. this._frontFace = value;
  10047. this._isFrontFaceDirty = true;
  10048. },
  10049. enumerable: true,
  10050. configurable: true
  10051. });
  10052. _DepthCullingState.prototype.reset = function () {
  10053. this._depthMask = true;
  10054. this._depthTest = true;
  10055. this._depthFunc = null;
  10056. this._cullFace = null;
  10057. this._cull = null;
  10058. this._zOffset = 0;
  10059. this._frontFace = null;
  10060. this._isDepthTestDirty = true;
  10061. this._isDepthMaskDirty = true;
  10062. this._isDepthFuncDirty = false;
  10063. this._isCullFaceDirty = false;
  10064. this._isCullDirty = false;
  10065. this._isZOffsetDirty = false;
  10066. this._isFrontFaceDirty = false;
  10067. };
  10068. _DepthCullingState.prototype.apply = function (gl) {
  10069. if (!this.isDirty) {
  10070. return;
  10071. }
  10072. // Cull
  10073. if (this._isCullDirty) {
  10074. if (this.cull) {
  10075. gl.enable(gl.CULL_FACE);
  10076. }
  10077. else {
  10078. gl.disable(gl.CULL_FACE);
  10079. }
  10080. this._isCullDirty = false;
  10081. }
  10082. // Cull face
  10083. if (this._isCullFaceDirty) {
  10084. gl.cullFace(this.cullFace);
  10085. this._isCullFaceDirty = false;
  10086. }
  10087. // Depth mask
  10088. if (this._isDepthMaskDirty) {
  10089. gl.depthMask(this.depthMask);
  10090. this._isDepthMaskDirty = false;
  10091. }
  10092. // Depth test
  10093. if (this._isDepthTestDirty) {
  10094. if (this.depthTest) {
  10095. gl.enable(gl.DEPTH_TEST);
  10096. }
  10097. else {
  10098. gl.disable(gl.DEPTH_TEST);
  10099. }
  10100. this._isDepthTestDirty = false;
  10101. }
  10102. // Depth func
  10103. if (this._isDepthFuncDirty) {
  10104. gl.depthFunc(this.depthFunc);
  10105. this._isDepthFuncDirty = false;
  10106. }
  10107. // zOffset
  10108. if (this._isZOffsetDirty) {
  10109. if (this.zOffset) {
  10110. gl.enable(gl.POLYGON_OFFSET_FILL);
  10111. gl.polygonOffset(this.zOffset, 0);
  10112. }
  10113. else {
  10114. gl.disable(gl.POLYGON_OFFSET_FILL);
  10115. }
  10116. this._isZOffsetDirty = false;
  10117. }
  10118. // Front face
  10119. if (this._isFrontFaceDirty) {
  10120. gl.frontFace(this.frontFace);
  10121. this._isFrontFaceDirty = false;
  10122. }
  10123. };
  10124. return _DepthCullingState;
  10125. }());
  10126. BABYLON._DepthCullingState = _DepthCullingState;
  10127. })(BABYLON || (BABYLON = {}));
  10128. //# sourceMappingURL=babylon.depthCullingState.js.map
  10129. "use strict";
  10130. var BABYLON;
  10131. (function (BABYLON) {
  10132. var _StencilState = /** @class */ (function () {
  10133. function _StencilState() {
  10134. this._isStencilTestDirty = false;
  10135. this._isStencilMaskDirty = false;
  10136. this._isStencilFuncDirty = false;
  10137. this._isStencilOpDirty = false;
  10138. this.reset();
  10139. }
  10140. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10141. get: function () {
  10142. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10143. },
  10144. enumerable: true,
  10145. configurable: true
  10146. });
  10147. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10148. get: function () {
  10149. return this._stencilFunc;
  10150. },
  10151. set: function (value) {
  10152. if (this._stencilFunc === value) {
  10153. return;
  10154. }
  10155. this._stencilFunc = value;
  10156. this._isStencilFuncDirty = true;
  10157. },
  10158. enumerable: true,
  10159. configurable: true
  10160. });
  10161. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10162. get: function () {
  10163. return this._stencilFuncRef;
  10164. },
  10165. set: function (value) {
  10166. if (this._stencilFuncRef === value) {
  10167. return;
  10168. }
  10169. this._stencilFuncRef = value;
  10170. this._isStencilFuncDirty = true;
  10171. },
  10172. enumerable: true,
  10173. configurable: true
  10174. });
  10175. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10176. get: function () {
  10177. return this._stencilFuncMask;
  10178. },
  10179. set: function (value) {
  10180. if (this._stencilFuncMask === value) {
  10181. return;
  10182. }
  10183. this._stencilFuncMask = value;
  10184. this._isStencilFuncDirty = true;
  10185. },
  10186. enumerable: true,
  10187. configurable: true
  10188. });
  10189. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10190. get: function () {
  10191. return this._stencilOpStencilFail;
  10192. },
  10193. set: function (value) {
  10194. if (this._stencilOpStencilFail === value) {
  10195. return;
  10196. }
  10197. this._stencilOpStencilFail = value;
  10198. this._isStencilOpDirty = true;
  10199. },
  10200. enumerable: true,
  10201. configurable: true
  10202. });
  10203. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10204. get: function () {
  10205. return this._stencilOpDepthFail;
  10206. },
  10207. set: function (value) {
  10208. if (this._stencilOpDepthFail === value) {
  10209. return;
  10210. }
  10211. this._stencilOpDepthFail = value;
  10212. this._isStencilOpDirty = true;
  10213. },
  10214. enumerable: true,
  10215. configurable: true
  10216. });
  10217. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10218. get: function () {
  10219. return this._stencilOpStencilDepthPass;
  10220. },
  10221. set: function (value) {
  10222. if (this._stencilOpStencilDepthPass === value) {
  10223. return;
  10224. }
  10225. this._stencilOpStencilDepthPass = value;
  10226. this._isStencilOpDirty = true;
  10227. },
  10228. enumerable: true,
  10229. configurable: true
  10230. });
  10231. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10232. get: function () {
  10233. return this._stencilMask;
  10234. },
  10235. set: function (value) {
  10236. if (this._stencilMask === value) {
  10237. return;
  10238. }
  10239. this._stencilMask = value;
  10240. this._isStencilMaskDirty = true;
  10241. },
  10242. enumerable: true,
  10243. configurable: true
  10244. });
  10245. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10246. get: function () {
  10247. return this._stencilTest;
  10248. },
  10249. set: function (value) {
  10250. if (this._stencilTest === value) {
  10251. return;
  10252. }
  10253. this._stencilTest = value;
  10254. this._isStencilTestDirty = true;
  10255. },
  10256. enumerable: true,
  10257. configurable: true
  10258. });
  10259. _StencilState.prototype.reset = function () {
  10260. this._stencilTest = false;
  10261. this._stencilMask = 0xFF;
  10262. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10263. this._stencilFuncRef = 1;
  10264. this._stencilFuncMask = 0xFF;
  10265. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10266. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10267. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10268. this._isStencilTestDirty = true;
  10269. this._isStencilMaskDirty = true;
  10270. this._isStencilFuncDirty = true;
  10271. this._isStencilOpDirty = true;
  10272. };
  10273. _StencilState.prototype.apply = function (gl) {
  10274. if (!this.isDirty) {
  10275. return;
  10276. }
  10277. // Stencil test
  10278. if (this._isStencilTestDirty) {
  10279. if (this.stencilTest) {
  10280. gl.enable(gl.STENCIL_TEST);
  10281. }
  10282. else {
  10283. gl.disable(gl.STENCIL_TEST);
  10284. }
  10285. this._isStencilTestDirty = false;
  10286. }
  10287. // Stencil mask
  10288. if (this._isStencilMaskDirty) {
  10289. gl.stencilMask(this.stencilMask);
  10290. this._isStencilMaskDirty = false;
  10291. }
  10292. // Stencil func
  10293. if (this._isStencilFuncDirty) {
  10294. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10295. this._isStencilFuncDirty = false;
  10296. }
  10297. // Stencil op
  10298. if (this._isStencilOpDirty) {
  10299. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10300. this._isStencilOpDirty = false;
  10301. }
  10302. };
  10303. return _StencilState;
  10304. }());
  10305. BABYLON._StencilState = _StencilState;
  10306. })(BABYLON || (BABYLON = {}));
  10307. //# sourceMappingURL=babylon.stencilState.js.map
  10308. "use strict";
  10309. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10310. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10311. s = arguments[i];
  10312. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10313. t[p] = s[p];
  10314. }
  10315. return t;
  10316. };
  10317. var BABYLON;
  10318. (function (BABYLON) {
  10319. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10320. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10321. };
  10322. var compileRawShader = function (gl, source, type) {
  10323. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10324. gl.shaderSource(shader, source);
  10325. gl.compileShader(shader);
  10326. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10327. var log = gl.getShaderInfoLog(shader);
  10328. if (log) {
  10329. throw new Error(log);
  10330. }
  10331. }
  10332. if (!shader) {
  10333. throw new Error("Something went wrong while compile the shader.");
  10334. }
  10335. return shader;
  10336. };
  10337. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10338. var magFilter = gl.NEAREST;
  10339. var minFilter = gl.NEAREST;
  10340. switch (samplingMode) {
  10341. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10342. magFilter = gl.LINEAR;
  10343. if (generateMipMaps) {
  10344. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10345. }
  10346. else {
  10347. minFilter = gl.LINEAR;
  10348. }
  10349. break;
  10350. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10351. magFilter = gl.LINEAR;
  10352. if (generateMipMaps) {
  10353. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10354. }
  10355. else {
  10356. minFilter = gl.LINEAR;
  10357. }
  10358. break;
  10359. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10360. magFilter = gl.NEAREST;
  10361. if (generateMipMaps) {
  10362. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10363. }
  10364. else {
  10365. minFilter = gl.NEAREST;
  10366. }
  10367. break;
  10368. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10369. magFilter = gl.NEAREST;
  10370. if (generateMipMaps) {
  10371. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10372. }
  10373. else {
  10374. minFilter = gl.NEAREST;
  10375. }
  10376. break;
  10377. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10378. magFilter = gl.NEAREST;
  10379. if (generateMipMaps) {
  10380. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10381. }
  10382. else {
  10383. minFilter = gl.LINEAR;
  10384. }
  10385. break;
  10386. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10387. magFilter = gl.NEAREST;
  10388. if (generateMipMaps) {
  10389. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10390. }
  10391. else {
  10392. minFilter = gl.LINEAR;
  10393. }
  10394. break;
  10395. case BABYLON.Texture.NEAREST_LINEAR:
  10396. magFilter = gl.NEAREST;
  10397. minFilter = gl.LINEAR;
  10398. break;
  10399. case BABYLON.Texture.NEAREST_NEAREST:
  10400. magFilter = gl.NEAREST;
  10401. minFilter = gl.NEAREST;
  10402. break;
  10403. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10404. magFilter = gl.LINEAR;
  10405. if (generateMipMaps) {
  10406. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10407. }
  10408. else {
  10409. minFilter = gl.NEAREST;
  10410. }
  10411. break;
  10412. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10413. magFilter = gl.LINEAR;
  10414. if (generateMipMaps) {
  10415. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10416. }
  10417. else {
  10418. minFilter = gl.NEAREST;
  10419. }
  10420. break;
  10421. case BABYLON.Texture.LINEAR_LINEAR:
  10422. magFilter = gl.LINEAR;
  10423. minFilter = gl.LINEAR;
  10424. break;
  10425. case BABYLON.Texture.LINEAR_NEAREST:
  10426. magFilter = gl.LINEAR;
  10427. minFilter = gl.NEAREST;
  10428. break;
  10429. }
  10430. return {
  10431. min: minFilter,
  10432. mag: magFilter
  10433. };
  10434. };
  10435. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10436. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10437. var img;
  10438. var onload = function () {
  10439. loadedImages[index] = img;
  10440. loadedImages._internalCount++;
  10441. if (scene) {
  10442. scene._removePendingData(img);
  10443. }
  10444. if (loadedImages._internalCount === 6) {
  10445. onfinish(loadedImages);
  10446. }
  10447. };
  10448. var onerror = function (message, exception) {
  10449. if (scene) {
  10450. scene._removePendingData(img);
  10451. }
  10452. if (onErrorCallBack) {
  10453. onErrorCallBack(message, exception);
  10454. }
  10455. };
  10456. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10457. if (scene) {
  10458. scene._addPendingData(img);
  10459. }
  10460. };
  10461. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10462. if (onError === void 0) { onError = null; }
  10463. var loadedImages = [];
  10464. loadedImages._internalCount = 0;
  10465. for (var index = 0; index < 6; index++) {
  10466. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10467. }
  10468. };
  10469. var BufferPointer = /** @class */ (function () {
  10470. function BufferPointer() {
  10471. }
  10472. return BufferPointer;
  10473. }());
  10474. /**
  10475. * Interface for attribute information associated with buffer instanciation
  10476. */
  10477. var InstancingAttributeInfo = /** @class */ (function () {
  10478. function InstancingAttributeInfo() {
  10479. }
  10480. return InstancingAttributeInfo;
  10481. }());
  10482. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10483. /**
  10484. * Define options used to create a render target texture
  10485. */
  10486. var RenderTargetCreationOptions = /** @class */ (function () {
  10487. function RenderTargetCreationOptions() {
  10488. }
  10489. return RenderTargetCreationOptions;
  10490. }());
  10491. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10492. /**
  10493. * Define options used to create a depth texture
  10494. */
  10495. var DepthTextureCreationOptions = /** @class */ (function () {
  10496. function DepthTextureCreationOptions() {
  10497. }
  10498. return DepthTextureCreationOptions;
  10499. }());
  10500. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  10501. /**
  10502. * Class used to describe the capabilities of the engine relatively to the current browser
  10503. */
  10504. var EngineCapabilities = /** @class */ (function () {
  10505. function EngineCapabilities() {
  10506. }
  10507. return EngineCapabilities;
  10508. }());
  10509. BABYLON.EngineCapabilities = EngineCapabilities;
  10510. /**
  10511. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  10512. */
  10513. var Engine = /** @class */ (function () {
  10514. /**
  10515. * Creates a new engine
  10516. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10517. * @param antialias defines enable antialiasing (default: false)
  10518. * @param options defines further options to be sent to the getContext() function
  10519. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10520. */
  10521. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10522. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10523. var _this = this;
  10524. // Public members
  10525. /**
  10526. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  10527. */
  10528. this.forcePOTTextures = false;
  10529. /**
  10530. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  10531. */
  10532. this.isFullscreen = false;
  10533. /**
  10534. * Gets a boolean indicating if the pointer is currently locked
  10535. */
  10536. this.isPointerLock = false;
  10537. /**
  10538. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  10539. */
  10540. this.cullBackFaces = true;
  10541. /**
  10542. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  10543. */
  10544. this.renderEvenInBackground = true;
  10545. /**
  10546. * Gets or sets a boolean indicating that cache can be kept between frames
  10547. */
  10548. this.preventCacheWipeBetweenFrames = false;
  10549. /**
  10550. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  10551. **/
  10552. this.enableOfflineSupport = false;
  10553. /**
  10554. * Gets the list of created scenes
  10555. */
  10556. this.scenes = new Array();
  10557. /**
  10558. * Gets the list of created postprocesses
  10559. */
  10560. this.postProcesses = new Array();
  10561. // Observables
  10562. /**
  10563. * Observable event triggered each time the rendering canvas is resized
  10564. */
  10565. this.onResizeObservable = new BABYLON.Observable();
  10566. /**
  10567. * Observable event triggered each time the canvas loses focus
  10568. */
  10569. this.onCanvasBlurObservable = new BABYLON.Observable();
  10570. /**
  10571. * Observable event triggered each time the canvas gains focus
  10572. */
  10573. this.onCanvasFocusObservable = new BABYLON.Observable();
  10574. /**
  10575. * Observable event triggered each time the canvas receives pointerout event
  10576. */
  10577. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10578. /**
  10579. * Observable event triggered before each texture is initialized
  10580. */
  10581. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10582. //WebVR
  10583. this._vrDisplay = undefined;
  10584. this._vrSupported = false;
  10585. this._vrExclusivePointerMode = false;
  10586. // Uniform buffers list
  10587. /**
  10588. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  10589. */
  10590. this.disableUniformBuffers = false;
  10591. /** @ignore */
  10592. this._uniformBuffers = new Array();
  10593. // Observables
  10594. /**
  10595. * Observable raised when the engine begins a new frame
  10596. */
  10597. this.onBeginFrameObservable = new BABYLON.Observable();
  10598. /**
  10599. * Observable raised when the engine ends the current frame
  10600. */
  10601. this.onEndFrameObservable = new BABYLON.Observable();
  10602. /**
  10603. * Observable raised when the engine is about to compile a shader
  10604. */
  10605. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10606. /**
  10607. * Observable raised when the engine has jsut compiled a shader
  10608. */
  10609. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10610. this._windowIsBackground = false;
  10611. this._webGLVersion = 1.0;
  10612. /** @ignore */
  10613. this._badOS = false;
  10614. /** @ignore */
  10615. this._badDesktopOS = false;
  10616. /**
  10617. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10618. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  10619. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  10620. */
  10621. this.disableTextureBindingOptimization = false;
  10622. /**
  10623. * Observable signaled when VR display mode changes
  10624. */
  10625. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10626. /**
  10627. * Observable signaled when VR request present is complete
  10628. */
  10629. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10630. /**
  10631. * Observable signaled when VR request present starts
  10632. */
  10633. this.onVRRequestPresentStart = new BABYLON.Observable();
  10634. this._colorWrite = true;
  10635. /** @ignore */
  10636. this._drawCalls = new BABYLON.PerfCounter();
  10637. /** @ignore */
  10638. this._textureCollisions = new BABYLON.PerfCounter();
  10639. this._renderingQueueLaunched = false;
  10640. this._activeRenderLoops = new Array();
  10641. // Deterministic lockstepMaxSteps
  10642. this._deterministicLockstep = false;
  10643. this._lockstepMaxSteps = 4;
  10644. // Lost context
  10645. /**
  10646. * Observable signaled when a context lost event is raised
  10647. */
  10648. this.onContextLostObservable = new BABYLON.Observable();
  10649. /**
  10650. * Observable signaled when a context restored event is raised
  10651. */
  10652. this.onContextRestoredObservable = new BABYLON.Observable();
  10653. this._contextWasLost = false;
  10654. this._doNotHandleContextLost = false;
  10655. // FPS
  10656. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10657. this._fps = 60;
  10658. this._deltaTime = 0;
  10659. /**
  10660. * Turn this value on if you want to pause FPS computation when in background
  10661. */
  10662. this.disablePerformanceMonitorInBackground = false;
  10663. // States
  10664. /** @ignore */
  10665. this._depthCullingState = new BABYLON._DepthCullingState();
  10666. /** @ignore */
  10667. this._stencilState = new BABYLON._StencilState();
  10668. /** @ignore */
  10669. this._alphaState = new BABYLON._AlphaState();
  10670. /** @ignore */
  10671. this._alphaMode = Engine.ALPHA_DISABLE;
  10672. // Cache
  10673. this._internalTexturesCache = new Array();
  10674. /** @ignore */
  10675. this._activeChannel = 0;
  10676. this._currentTextureChannel = -1;
  10677. /** @ignore */
  10678. this._boundTexturesCache = {};
  10679. this._compiledEffects = {};
  10680. this._vertexAttribArraysEnabled = [];
  10681. this._uintIndicesCurrentlySet = false;
  10682. this._currentBoundBuffer = new Array();
  10683. this._currentBufferPointers = new Array();
  10684. this._currentInstanceLocations = new Array();
  10685. this._currentInstanceBuffers = new Array();
  10686. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10687. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10688. this._vaoRecordInProgress = false;
  10689. this._mustWipeVertexAttributes = false;
  10690. this._nextFreeTextureSlots = new Array();
  10691. this._maxSimultaneousTextures = 0;
  10692. this._activeRequests = new Array();
  10693. // Hardware supported Compressed Textures
  10694. this._texturesSupported = new Array();
  10695. this._onVRFullScreenTriggered = function () {
  10696. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10697. //get the old size before we change
  10698. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10699. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10700. //get the width and height, change the render size
  10701. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10702. _this.setHardwareScalingLevel(1);
  10703. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10704. }
  10705. else {
  10706. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10707. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10708. }
  10709. };
  10710. this._boundUniforms = {};
  10711. // Register promises
  10712. BABYLON.PromisePolyfill.Apply();
  10713. var canvas = null;
  10714. Engine.Instances.push(this);
  10715. if (!canvasOrContext) {
  10716. return;
  10717. }
  10718. options = options || {};
  10719. if (canvasOrContext.getContext) {
  10720. canvas = canvasOrContext;
  10721. this._renderingCanvas = canvas;
  10722. if (antialias != null) {
  10723. options.antialias = antialias;
  10724. }
  10725. if (options.deterministicLockstep === undefined) {
  10726. options.deterministicLockstep = false;
  10727. }
  10728. if (options.lockstepMaxSteps === undefined) {
  10729. options.lockstepMaxSteps = 4;
  10730. }
  10731. if (options.preserveDrawingBuffer === undefined) {
  10732. options.preserveDrawingBuffer = false;
  10733. }
  10734. if (options.audioEngine === undefined) {
  10735. options.audioEngine = true;
  10736. }
  10737. if (options.stencil === undefined) {
  10738. options.stencil = true;
  10739. }
  10740. this._deterministicLockstep = options.deterministicLockstep;
  10741. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10742. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10743. // Exceptions
  10744. if (navigator && navigator.userAgent) {
  10745. var ua = navigator.userAgent;
  10746. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10747. var exception = _a[_i];
  10748. var key = exception.key;
  10749. var targets = exception.targets;
  10750. if (ua.indexOf(key) > -1) {
  10751. if (exception.capture && exception.captureConstraint) {
  10752. var capture = exception.capture;
  10753. var constraint = exception.captureConstraint;
  10754. var regex = new RegExp(capture);
  10755. var matches = regex.exec(ua);
  10756. if (matches && matches.length > 0) {
  10757. var capturedValue = parseInt(matches[matches.length - 1]);
  10758. if (capturedValue >= constraint) {
  10759. continue;
  10760. }
  10761. }
  10762. }
  10763. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10764. var target = targets_1[_b];
  10765. switch (target) {
  10766. case "uniformBuffer":
  10767. this.disableUniformBuffers = true;
  10768. break;
  10769. case "textureBindingOptimization":
  10770. this.disableTextureBindingOptimization = true;
  10771. break;
  10772. }
  10773. }
  10774. }
  10775. }
  10776. }
  10777. // GL
  10778. if (!options.disableWebGL2Support) {
  10779. try {
  10780. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10781. if (this._gl) {
  10782. this._webGLVersion = 2.0;
  10783. }
  10784. }
  10785. catch (e) {
  10786. // Do nothing
  10787. }
  10788. }
  10789. if (!this._gl) {
  10790. if (!canvas) {
  10791. throw new Error("The provided canvas is null or undefined.");
  10792. }
  10793. try {
  10794. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10795. }
  10796. catch (e) {
  10797. throw new Error("WebGL not supported");
  10798. }
  10799. }
  10800. if (!this._gl) {
  10801. throw new Error("WebGL not supported");
  10802. }
  10803. this._onCanvasFocus = function () {
  10804. _this.onCanvasFocusObservable.notifyObservers(_this);
  10805. };
  10806. this._onCanvasBlur = function () {
  10807. _this.onCanvasBlurObservable.notifyObservers(_this);
  10808. };
  10809. canvas.addEventListener("focus", this._onCanvasFocus);
  10810. canvas.addEventListener("blur", this._onCanvasBlur);
  10811. this._onBlur = function () {
  10812. if (_this.disablePerformanceMonitorInBackground) {
  10813. _this._performanceMonitor.disable();
  10814. }
  10815. _this._windowIsBackground = true;
  10816. };
  10817. this._onFocus = function () {
  10818. if (_this.disablePerformanceMonitorInBackground) {
  10819. _this._performanceMonitor.enable();
  10820. }
  10821. _this._windowIsBackground = false;
  10822. };
  10823. this._onCanvasPointerOut = function (ev) {
  10824. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  10825. };
  10826. window.addEventListener("blur", this._onBlur);
  10827. window.addEventListener("focus", this._onFocus);
  10828. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10829. // Context lost
  10830. if (!this._doNotHandleContextLost) {
  10831. this._onContextLost = function (evt) {
  10832. evt.preventDefault();
  10833. _this._contextWasLost = true;
  10834. BABYLON.Tools.Warn("WebGL context lost.");
  10835. _this.onContextLostObservable.notifyObservers(_this);
  10836. };
  10837. this._onContextRestored = function (evt) {
  10838. // Adding a timeout to avoid race condition at browser level
  10839. setTimeout(function () {
  10840. // Rebuild gl context
  10841. _this._initGLContext();
  10842. // Rebuild effects
  10843. _this._rebuildEffects();
  10844. // Rebuild textures
  10845. _this._rebuildInternalTextures();
  10846. // Rebuild buffers
  10847. _this._rebuildBuffers();
  10848. // Cache
  10849. _this.wipeCaches(true);
  10850. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10851. _this.onContextRestoredObservable.notifyObservers(_this);
  10852. _this._contextWasLost = false;
  10853. }, 0);
  10854. };
  10855. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10856. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10857. }
  10858. }
  10859. else {
  10860. this._gl = canvasOrContext;
  10861. this._renderingCanvas = this._gl.canvas;
  10862. if (this._gl.renderbufferStorageMultisample) {
  10863. this._webGLVersion = 2.0;
  10864. }
  10865. options.stencil = this._gl.getContextAttributes().stencil;
  10866. }
  10867. // Viewport
  10868. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10869. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10870. this.resize();
  10871. this._isStencilEnable = options.stencil ? true : false;
  10872. this._initGLContext();
  10873. if (canvas) {
  10874. // Fullscreen
  10875. this._onFullscreenChange = function () {
  10876. if (document.fullscreen !== undefined) {
  10877. _this.isFullscreen = document.fullscreen;
  10878. }
  10879. else if (document.mozFullScreen !== undefined) {
  10880. _this.isFullscreen = document.mozFullScreen;
  10881. }
  10882. else if (document.webkitIsFullScreen !== undefined) {
  10883. _this.isFullscreen = document.webkitIsFullScreen;
  10884. }
  10885. else if (document.msIsFullScreen !== undefined) {
  10886. _this.isFullscreen = document.msIsFullScreen;
  10887. }
  10888. // Pointer lock
  10889. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10890. canvas.requestPointerLock = canvas.requestPointerLock ||
  10891. canvas.msRequestPointerLock ||
  10892. canvas.mozRequestPointerLock ||
  10893. canvas.webkitRequestPointerLock;
  10894. if (canvas.requestPointerLock) {
  10895. canvas.requestPointerLock();
  10896. }
  10897. }
  10898. };
  10899. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10900. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10901. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10902. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10903. // Pointer lock
  10904. this._onPointerLockChange = function () {
  10905. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10906. document.webkitPointerLockElement === canvas ||
  10907. document.msPointerLockElement === canvas ||
  10908. document.pointerLockElement === canvas);
  10909. };
  10910. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10911. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10912. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10913. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10914. this._onVRDisplayPointerRestricted = function () {
  10915. if (canvas) {
  10916. canvas.requestPointerLock();
  10917. }
  10918. };
  10919. this._onVRDisplayPointerUnrestricted = function () {
  10920. document.exitPointerLock();
  10921. };
  10922. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10923. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10924. }
  10925. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10926. Engine.audioEngine = new BABYLON.AudioEngine();
  10927. }
  10928. // Prepare buffer pointers
  10929. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10930. this._currentBufferPointers[i] = new BufferPointer();
  10931. }
  10932. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10933. // Load WebVR Devices
  10934. if (options.autoEnableWebVR) {
  10935. this.initWebVR();
  10936. }
  10937. // Detect if we are running on a faulty buggy OS.
  10938. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10939. // Detect if we are running on a faulty buggy desktop OS.
  10940. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10941. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  10942. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10943. }
  10944. Object.defineProperty(Engine, "LastCreatedEngine", {
  10945. /**
  10946. * Gets the latest created engine
  10947. */
  10948. get: function () {
  10949. if (Engine.Instances.length === 0) {
  10950. return null;
  10951. }
  10952. return Engine.Instances[Engine.Instances.length - 1];
  10953. },
  10954. enumerable: true,
  10955. configurable: true
  10956. });
  10957. Object.defineProperty(Engine, "LastCreatedScene", {
  10958. /**
  10959. * Gets the latest created scene
  10960. */
  10961. get: function () {
  10962. var lastCreatedEngine = Engine.LastCreatedEngine;
  10963. if (!lastCreatedEngine) {
  10964. return null;
  10965. }
  10966. if (lastCreatedEngine.scenes.length === 0) {
  10967. return null;
  10968. }
  10969. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10970. },
  10971. enumerable: true,
  10972. configurable: true
  10973. });
  10974. /**
  10975. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10976. * @param flag defines which part of the materials must be marked as dirty
  10977. * @param predicate defines a predicate used to filter which materials should be affected
  10978. */
  10979. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10980. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10981. var engine = Engine.Instances[engineIndex];
  10982. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10983. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10984. }
  10985. }
  10986. };
  10987. Object.defineProperty(Engine, "NEVER", {
  10988. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  10989. get: function () {
  10990. return Engine._NEVER;
  10991. },
  10992. enumerable: true,
  10993. configurable: true
  10994. });
  10995. Object.defineProperty(Engine, "ALWAYS", {
  10996. /** 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 */
  10997. get: function () {
  10998. return Engine._ALWAYS;
  10999. },
  11000. enumerable: true,
  11001. configurable: true
  11002. });
  11003. Object.defineProperty(Engine, "LESS", {
  11004. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11005. get: function () {
  11006. return Engine._LESS;
  11007. },
  11008. enumerable: true,
  11009. configurable: true
  11010. });
  11011. Object.defineProperty(Engine, "EQUAL", {
  11012. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11013. get: function () {
  11014. return Engine._EQUAL;
  11015. },
  11016. enumerable: true,
  11017. configurable: true
  11018. });
  11019. Object.defineProperty(Engine, "LEQUAL", {
  11020. /** 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 */
  11021. get: function () {
  11022. return Engine._LEQUAL;
  11023. },
  11024. enumerable: true,
  11025. configurable: true
  11026. });
  11027. Object.defineProperty(Engine, "GREATER", {
  11028. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11029. get: function () {
  11030. return Engine._GREATER;
  11031. },
  11032. enumerable: true,
  11033. configurable: true
  11034. });
  11035. Object.defineProperty(Engine, "GEQUAL", {
  11036. /** 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 */
  11037. get: function () {
  11038. return Engine._GEQUAL;
  11039. },
  11040. enumerable: true,
  11041. configurable: true
  11042. });
  11043. Object.defineProperty(Engine, "NOTEQUAL", {
  11044. /** 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 */
  11045. get: function () {
  11046. return Engine._NOTEQUAL;
  11047. },
  11048. enumerable: true,
  11049. configurable: true
  11050. });
  11051. Object.defineProperty(Engine, "KEEP", {
  11052. /** Passed to stencilOperation to specify that stencil value must be kept */
  11053. get: function () {
  11054. return Engine._KEEP;
  11055. },
  11056. enumerable: true,
  11057. configurable: true
  11058. });
  11059. Object.defineProperty(Engine, "REPLACE", {
  11060. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11061. get: function () {
  11062. return Engine._REPLACE;
  11063. },
  11064. enumerable: true,
  11065. configurable: true
  11066. });
  11067. Object.defineProperty(Engine, "INCR", {
  11068. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11069. get: function () {
  11070. return Engine._INCR;
  11071. },
  11072. enumerable: true,
  11073. configurable: true
  11074. });
  11075. Object.defineProperty(Engine, "DECR", {
  11076. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11077. get: function () {
  11078. return Engine._DECR;
  11079. },
  11080. enumerable: true,
  11081. configurable: true
  11082. });
  11083. Object.defineProperty(Engine, "INVERT", {
  11084. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11085. get: function () {
  11086. return Engine._INVERT;
  11087. },
  11088. enumerable: true,
  11089. configurable: true
  11090. });
  11091. Object.defineProperty(Engine, "INCR_WRAP", {
  11092. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11093. get: function () {
  11094. return Engine._INCR_WRAP;
  11095. },
  11096. enumerable: true,
  11097. configurable: true
  11098. });
  11099. Object.defineProperty(Engine, "DECR_WRAP", {
  11100. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11101. get: function () {
  11102. return Engine._DECR_WRAP;
  11103. },
  11104. enumerable: true,
  11105. configurable: true
  11106. });
  11107. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11108. // Alpha
  11109. /** Defines that alpha blending is disabled */
  11110. get: function () {
  11111. return Engine._ALPHA_DISABLE;
  11112. },
  11113. enumerable: true,
  11114. configurable: true
  11115. });
  11116. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11117. /** Defines that alpha blending to SRC + DEST */
  11118. get: function () {
  11119. return Engine._ALPHA_ONEONE;
  11120. },
  11121. enumerable: true,
  11122. configurable: true
  11123. });
  11124. Object.defineProperty(Engine, "ALPHA_ADD", {
  11125. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11126. get: function () {
  11127. return Engine._ALPHA_ADD;
  11128. },
  11129. enumerable: true,
  11130. configurable: true
  11131. });
  11132. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11133. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11134. get: function () {
  11135. return Engine._ALPHA_COMBINE;
  11136. },
  11137. enumerable: true,
  11138. configurable: true
  11139. });
  11140. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11141. /** Defines that alpha blending to DEST - SRC * DEST */
  11142. get: function () {
  11143. return Engine._ALPHA_SUBTRACT;
  11144. },
  11145. enumerable: true,
  11146. configurable: true
  11147. });
  11148. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11149. /** Defines that alpha blending to SRC * DEST */
  11150. get: function () {
  11151. return Engine._ALPHA_MULTIPLY;
  11152. },
  11153. enumerable: true,
  11154. configurable: true
  11155. });
  11156. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11157. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11158. get: function () {
  11159. return Engine._ALPHA_MAXIMIZED;
  11160. },
  11161. enumerable: true,
  11162. configurable: true
  11163. });
  11164. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11165. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11166. get: function () {
  11167. return Engine._ALPHA_PREMULTIPLIED;
  11168. },
  11169. enumerable: true,
  11170. configurable: true
  11171. });
  11172. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11173. /**
  11174. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11175. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11176. */
  11177. get: function () {
  11178. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11179. },
  11180. enumerable: true,
  11181. configurable: true
  11182. });
  11183. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11184. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11185. get: function () {
  11186. return Engine._ALPHA_INTERPOLATE;
  11187. },
  11188. enumerable: true,
  11189. configurable: true
  11190. });
  11191. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11192. /**
  11193. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11194. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11195. */
  11196. get: function () {
  11197. return Engine._ALPHA_SCREENMODE;
  11198. },
  11199. enumerable: true,
  11200. configurable: true
  11201. });
  11202. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11203. // Delays
  11204. /** Defines that the ressource is not delayed*/
  11205. get: function () {
  11206. return Engine._DELAYLOADSTATE_NONE;
  11207. },
  11208. enumerable: true,
  11209. configurable: true
  11210. });
  11211. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11212. /** Defines that the ressource was successfully delay loaded */
  11213. get: function () {
  11214. return Engine._DELAYLOADSTATE_LOADED;
  11215. },
  11216. enumerable: true,
  11217. configurable: true
  11218. });
  11219. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11220. /** Defines that the ressource is currently delay loading */
  11221. get: function () {
  11222. return Engine._DELAYLOADSTATE_LOADING;
  11223. },
  11224. enumerable: true,
  11225. configurable: true
  11226. });
  11227. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11228. /** Defines that the ressource is delayed and has not started loading */
  11229. get: function () {
  11230. return Engine._DELAYLOADSTATE_NOTLOADED;
  11231. },
  11232. enumerable: true,
  11233. configurable: true
  11234. });
  11235. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11236. /** ALPHA */
  11237. get: function () {
  11238. return Engine._TEXTUREFORMAT_ALPHA;
  11239. },
  11240. enumerable: true,
  11241. configurable: true
  11242. });
  11243. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11244. /** LUMINANCE */
  11245. get: function () {
  11246. return Engine._TEXTUREFORMAT_LUMINANCE;
  11247. },
  11248. enumerable: true,
  11249. configurable: true
  11250. });
  11251. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11252. /**
  11253. * R32F
  11254. */
  11255. get: function () {
  11256. return Engine._TEXTUREFORMAT_R32F;
  11257. },
  11258. enumerable: true,
  11259. configurable: true
  11260. });
  11261. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11262. /**
  11263. * RG32F
  11264. */
  11265. get: function () {
  11266. return Engine._TEXTUREFORMAT_RG32F;
  11267. },
  11268. enumerable: true,
  11269. configurable: true
  11270. });
  11271. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11272. /**
  11273. * RGB32F
  11274. */
  11275. get: function () {
  11276. return Engine._TEXTUREFORMAT_RGB32F;
  11277. },
  11278. enumerable: true,
  11279. configurable: true
  11280. });
  11281. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11282. /**
  11283. * RGBA32F
  11284. */
  11285. get: function () {
  11286. return Engine._TEXTUREFORMAT_RGBA32F;
  11287. },
  11288. enumerable: true,
  11289. configurable: true
  11290. });
  11291. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11292. /** LUMINANCE_ALPHA */
  11293. get: function () {
  11294. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11295. },
  11296. enumerable: true,
  11297. configurable: true
  11298. });
  11299. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11300. /** RGB */
  11301. get: function () {
  11302. return Engine._TEXTUREFORMAT_RGB;
  11303. },
  11304. enumerable: true,
  11305. configurable: true
  11306. });
  11307. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11308. /** RGBA */
  11309. get: function () {
  11310. return Engine._TEXTUREFORMAT_RGBA;
  11311. },
  11312. enumerable: true,
  11313. configurable: true
  11314. });
  11315. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11316. /** UNSIGNED_INT */
  11317. get: function () {
  11318. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11319. },
  11320. enumerable: true,
  11321. configurable: true
  11322. });
  11323. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11324. /** FLOAT */
  11325. get: function () {
  11326. return Engine._TEXTURETYPE_FLOAT;
  11327. },
  11328. enumerable: true,
  11329. configurable: true
  11330. });
  11331. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11332. /** HALF_FLOAT */
  11333. get: function () {
  11334. return Engine._TEXTURETYPE_HALF_FLOAT;
  11335. },
  11336. enumerable: true,
  11337. configurable: true
  11338. });
  11339. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11340. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  11341. get: function () {
  11342. return Engine._SCALEMODE_FLOOR;
  11343. },
  11344. enumerable: true,
  11345. configurable: true
  11346. });
  11347. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11348. /** Defines that texture rescaling will look for the nearest power of 2 size */
  11349. get: function () {
  11350. return Engine._SCALEMODE_NEAREST;
  11351. },
  11352. enumerable: true,
  11353. configurable: true
  11354. });
  11355. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11356. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  11357. get: function () {
  11358. return Engine._SCALEMODE_CEILING;
  11359. },
  11360. enumerable: true,
  11361. configurable: true
  11362. });
  11363. Object.defineProperty(Engine, "Version", {
  11364. /**
  11365. * Returns the current version of the framework
  11366. */
  11367. get: function () {
  11368. return "3.2.0-beta.3";
  11369. },
  11370. enumerable: true,
  11371. configurable: true
  11372. });
  11373. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11374. /**
  11375. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11376. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11377. */
  11378. get: function () {
  11379. return this._vrExclusivePointerMode;
  11380. },
  11381. enumerable: true,
  11382. configurable: true
  11383. });
  11384. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11385. /**
  11386. * Gets a boolean indicating that the engine supports uniform buffers
  11387. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11388. */
  11389. get: function () {
  11390. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11391. },
  11392. enumerable: true,
  11393. configurable: true
  11394. });
  11395. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11396. /**
  11397. * Gets a boolean indicating that only power of 2 textures are supported
  11398. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11399. */
  11400. get: function () {
  11401. return this._webGLVersion < 2 || this.forcePOTTextures;
  11402. },
  11403. enumerable: true,
  11404. configurable: true
  11405. });
  11406. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11407. /**
  11408. * Gets the performance monitor attached to this engine
  11409. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  11410. */
  11411. get: function () {
  11412. return this._performanceMonitor;
  11413. },
  11414. enumerable: true,
  11415. configurable: true
  11416. });
  11417. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11418. /**
  11419. * Gets the list of texture formats supported
  11420. */
  11421. get: function () {
  11422. return this._texturesSupported;
  11423. },
  11424. enumerable: true,
  11425. configurable: true
  11426. });
  11427. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11428. /**
  11429. * Gets the list of texture formats in use
  11430. */
  11431. get: function () {
  11432. return this._textureFormatInUse;
  11433. },
  11434. enumerable: true,
  11435. configurable: true
  11436. });
  11437. Object.defineProperty(Engine.prototype, "currentViewport", {
  11438. /**
  11439. * Gets the current viewport
  11440. */
  11441. get: function () {
  11442. return this._cachedViewport;
  11443. },
  11444. enumerable: true,
  11445. configurable: true
  11446. });
  11447. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11448. /**
  11449. * Gets the default empty texture
  11450. */
  11451. get: function () {
  11452. if (!this._emptyTexture) {
  11453. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11454. }
  11455. return this._emptyTexture;
  11456. },
  11457. enumerable: true,
  11458. configurable: true
  11459. });
  11460. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11461. /**
  11462. * Gets the default empty 3D texture
  11463. */
  11464. get: function () {
  11465. if (!this._emptyTexture3D) {
  11466. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11467. }
  11468. return this._emptyTexture3D;
  11469. },
  11470. enumerable: true,
  11471. configurable: true
  11472. });
  11473. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11474. /**
  11475. * Gets the default empty cube texture
  11476. */
  11477. get: function () {
  11478. if (!this._emptyCubeTexture) {
  11479. var faceData = new Uint8Array(4);
  11480. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11481. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11482. }
  11483. return this._emptyCubeTexture;
  11484. },
  11485. enumerable: true,
  11486. configurable: true
  11487. });
  11488. Engine.prototype._rebuildInternalTextures = function () {
  11489. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11490. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11491. var internalTexture = currentState_1[_i];
  11492. internalTexture._rebuild();
  11493. }
  11494. };
  11495. Engine.prototype._rebuildEffects = function () {
  11496. for (var key in this._compiledEffects) {
  11497. var effect = this._compiledEffects[key];
  11498. effect._prepareEffect();
  11499. }
  11500. BABYLON.Effect.ResetCache();
  11501. };
  11502. Engine.prototype._rebuildBuffers = function () {
  11503. // Index / Vertex
  11504. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11505. var scene = _a[_i];
  11506. scene.resetCachedMaterial();
  11507. scene._rebuildGeometries();
  11508. scene._rebuildTextures();
  11509. }
  11510. // Uniforms
  11511. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11512. var uniformBuffer = _c[_b];
  11513. uniformBuffer._rebuild();
  11514. }
  11515. };
  11516. Engine.prototype._initGLContext = function () {
  11517. // Caps
  11518. this._caps = new EngineCapabilities();
  11519. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11520. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11521. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11522. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11523. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11524. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11525. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11526. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11527. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11528. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11529. // Infos
  11530. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11531. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11532. if (rendererInfo != null) {
  11533. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11534. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11535. }
  11536. if (!this._glVendor) {
  11537. this._glVendor = "Unknown vendor";
  11538. }
  11539. if (!this._glRenderer) {
  11540. this._glRenderer = "Unknown renderer";
  11541. }
  11542. // Constants
  11543. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11544. if (this._gl.RGBA16F !== 0x881A) {
  11545. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11546. }
  11547. if (this._gl.RGBA32F !== 0x8814) {
  11548. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11549. }
  11550. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11551. this._gl.DEPTH24_STENCIL8 = 35056;
  11552. }
  11553. // Extensions
  11554. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11555. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11556. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11557. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11558. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11559. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11560. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11561. 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');
  11562. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11563. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11564. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11565. this._caps.highPrecisionShaderSupported = true;
  11566. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11567. if (this._caps.timerQuery) {
  11568. if (this._webGLVersion === 1) {
  11569. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11570. }
  11571. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11572. }
  11573. // Checks if some of the format renders first to allow the use of webgl inspector.
  11574. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11575. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  11576. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  11577. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  11578. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  11579. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  11580. if (this._webGLVersion > 1) {
  11581. this._gl.HALF_FLOAT_OES = 0x140B;
  11582. }
  11583. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11584. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  11585. // Draw buffers
  11586. if (this._webGLVersion > 1) {
  11587. this._caps.drawBuffersExtension = true;
  11588. }
  11589. else {
  11590. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11591. if (drawBuffersExtension !== null) {
  11592. this._caps.drawBuffersExtension = true;
  11593. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11594. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11595. for (var i = 0; i < 16; i++) {
  11596. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11597. }
  11598. }
  11599. else {
  11600. this._caps.drawBuffersExtension = false;
  11601. }
  11602. }
  11603. // Depth Texture
  11604. if (this._webGLVersion > 1) {
  11605. this._caps.depthTextureExtension = true;
  11606. }
  11607. else {
  11608. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11609. if (depthTextureExtension != null) {
  11610. this._caps.depthTextureExtension = true;
  11611. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11612. }
  11613. }
  11614. // Vertex array object
  11615. if (this._webGLVersion > 1) {
  11616. this._caps.vertexArrayObject = true;
  11617. }
  11618. else {
  11619. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11620. if (vertexArrayObjectExtension != null) {
  11621. this._caps.vertexArrayObject = true;
  11622. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11623. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11624. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11625. }
  11626. else {
  11627. this._caps.vertexArrayObject = false;
  11628. }
  11629. }
  11630. // Instances count
  11631. if (this._webGLVersion > 1) {
  11632. this._caps.instancedArrays = true;
  11633. }
  11634. else {
  11635. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11636. if (instanceExtension != null) {
  11637. this._caps.instancedArrays = true;
  11638. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11639. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11640. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11641. }
  11642. else {
  11643. this._caps.instancedArrays = false;
  11644. }
  11645. }
  11646. // Intelligently add supported compressed formats in order to check for.
  11647. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11648. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11649. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11650. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11651. if (this._caps.astc)
  11652. this.texturesSupported.push('-astc.ktx');
  11653. if (this._caps.s3tc)
  11654. this.texturesSupported.push('-dxt.ktx');
  11655. if (this._caps.pvrtc)
  11656. this.texturesSupported.push('-pvrtc.ktx');
  11657. if (this._caps.etc2)
  11658. this.texturesSupported.push('-etc2.ktx');
  11659. if (this._caps.etc1)
  11660. this.texturesSupported.push('-etc1.ktx');
  11661. if (this._gl.getShaderPrecisionFormat) {
  11662. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11663. if (highp) {
  11664. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11665. }
  11666. }
  11667. // Depth buffer
  11668. this.setDepthBuffer(true);
  11669. this.setDepthFunctionToLessOrEqual();
  11670. this.setDepthWrite(true);
  11671. // Texture maps
  11672. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11673. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11674. this._nextFreeTextureSlots.push(slot);
  11675. }
  11676. };
  11677. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11678. /**
  11679. * Gets version of the current webGL context
  11680. */
  11681. get: function () {
  11682. return this._webGLVersion;
  11683. },
  11684. enumerable: true,
  11685. configurable: true
  11686. });
  11687. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11688. /**
  11689. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11690. */
  11691. get: function () {
  11692. return this._isStencilEnable;
  11693. },
  11694. enumerable: true,
  11695. configurable: true
  11696. });
  11697. Engine.prototype._prepareWorkingCanvas = function () {
  11698. if (this._workingCanvas) {
  11699. return;
  11700. }
  11701. this._workingCanvas = document.createElement("canvas");
  11702. var context = this._workingCanvas.getContext("2d");
  11703. if (context) {
  11704. this._workingContext = context;
  11705. }
  11706. };
  11707. /**
  11708. * Reset the texture cache to empty state
  11709. */
  11710. Engine.prototype.resetTextureCache = function () {
  11711. for (var key in this._boundTexturesCache) {
  11712. var boundTexture = this._boundTexturesCache[key];
  11713. if (boundTexture) {
  11714. this._removeDesignatedSlot(boundTexture);
  11715. }
  11716. this._boundTexturesCache[key] = null;
  11717. }
  11718. if (!this.disableTextureBindingOptimization) {
  11719. this._nextFreeTextureSlots = [];
  11720. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11721. this._nextFreeTextureSlots.push(slot);
  11722. }
  11723. }
  11724. this._currentTextureChannel = -1;
  11725. };
  11726. /**
  11727. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  11728. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  11729. * @returns true if engine is in deterministic lock step mode
  11730. */
  11731. Engine.prototype.isDeterministicLockStep = function () {
  11732. return this._deterministicLockstep;
  11733. };
  11734. /**
  11735. * Gets the max steps when engine is running in deterministic lock step
  11736. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  11737. * @returns the max steps
  11738. */
  11739. Engine.prototype.getLockstepMaxSteps = function () {
  11740. return this._lockstepMaxSteps;
  11741. };
  11742. /**
  11743. * Gets an object containing information about the current webGL context
  11744. * @returns an object containing the vender, the renderer and the version of the current webGL context
  11745. */
  11746. Engine.prototype.getGlInfo = function () {
  11747. return {
  11748. vendor: this._glVendor,
  11749. renderer: this._glRenderer,
  11750. version: this._glVersion
  11751. };
  11752. };
  11753. /**
  11754. * Gets current aspect ratio
  11755. * @param camera defines the camera to use to get the aspect ratio
  11756. * @param useScreen defines if screen size must be used (or the current render target if any)
  11757. * @returns a number defining the aspect ratio
  11758. */
  11759. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11760. if (useScreen === void 0) { useScreen = false; }
  11761. var viewport = camera.viewport;
  11762. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11763. };
  11764. /**
  11765. * Gets the current render width
  11766. * @param useScreen defines if screen size must be used (or the current render target if any)
  11767. * @returns a number defining the current render width
  11768. */
  11769. Engine.prototype.getRenderWidth = function (useScreen) {
  11770. if (useScreen === void 0) { useScreen = false; }
  11771. if (!useScreen && this._currentRenderTarget) {
  11772. return this._currentRenderTarget.width;
  11773. }
  11774. return this._gl.drawingBufferWidth;
  11775. };
  11776. /**
  11777. * Gets the current render height
  11778. * @param useScreen defines if screen size must be used (or the current render target if any)
  11779. * @returns a number defining the current render height
  11780. */
  11781. Engine.prototype.getRenderHeight = function (useScreen) {
  11782. if (useScreen === void 0) { useScreen = false; }
  11783. if (!useScreen && this._currentRenderTarget) {
  11784. return this._currentRenderTarget.height;
  11785. }
  11786. return this._gl.drawingBufferHeight;
  11787. };
  11788. /**
  11789. * Gets the HTML canvas attached with the current webGL context
  11790. * @returns a HTML canvas
  11791. */
  11792. Engine.prototype.getRenderingCanvas = function () {
  11793. return this._renderingCanvas;
  11794. };
  11795. /**
  11796. * Gets the client rect of the HTML canvas attached with the current webGL context
  11797. * @returns a client rectanglee
  11798. */
  11799. Engine.prototype.getRenderingCanvasClientRect = function () {
  11800. if (!this._renderingCanvas) {
  11801. return null;
  11802. }
  11803. return this._renderingCanvas.getBoundingClientRect();
  11804. };
  11805. /**
  11806. * Defines the hardware scaling level.
  11807. * By default the hardware scaling level is computed from the window device ratio.
  11808. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  11809. * @param level defines the level to use
  11810. */
  11811. Engine.prototype.setHardwareScalingLevel = function (level) {
  11812. this._hardwareScalingLevel = level;
  11813. this.resize();
  11814. };
  11815. /**
  11816. * Gets the current hardware scaling level.
  11817. * By default the hardware scaling level is computed from the window device ratio.
  11818. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  11819. * @returns a number indicating the current hardware scaling level
  11820. */
  11821. Engine.prototype.getHardwareScalingLevel = function () {
  11822. return this._hardwareScalingLevel;
  11823. };
  11824. /**
  11825. * Gets the list of loaded textures
  11826. * @returns an array containing all loaded textures
  11827. */
  11828. Engine.prototype.getLoadedTexturesCache = function () {
  11829. return this._internalTexturesCache;
  11830. };
  11831. /**
  11832. * Gets the object containing all engine capabilities
  11833. * @returns the EngineCapabilities object
  11834. */
  11835. Engine.prototype.getCaps = function () {
  11836. return this._caps;
  11837. };
  11838. Object.defineProperty(Engine.prototype, "drawCalls", {
  11839. /** @ignore */
  11840. get: function () {
  11841. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11842. return 0;
  11843. },
  11844. enumerable: true,
  11845. configurable: true
  11846. });
  11847. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11848. /** @ignore */
  11849. get: function () {
  11850. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11851. return null;
  11852. },
  11853. enumerable: true,
  11854. configurable: true
  11855. });
  11856. /**
  11857. * Gets the current depth function
  11858. * @returns a number defining the depth function
  11859. */
  11860. Engine.prototype.getDepthFunction = function () {
  11861. return this._depthCullingState.depthFunc;
  11862. };
  11863. /**
  11864. * Sets the current depth function
  11865. * @param depthFunc defines the function to use
  11866. */
  11867. Engine.prototype.setDepthFunction = function (depthFunc) {
  11868. this._depthCullingState.depthFunc = depthFunc;
  11869. };
  11870. /**
  11871. * Sets the current depth function to GREATER
  11872. */
  11873. Engine.prototype.setDepthFunctionToGreater = function () {
  11874. this._depthCullingState.depthFunc = this._gl.GREATER;
  11875. };
  11876. /**
  11877. * Sets the current depth function to GEQUAL
  11878. */
  11879. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11880. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11881. };
  11882. /**
  11883. * Sets the current depth function to LESS
  11884. */
  11885. Engine.prototype.setDepthFunctionToLess = function () {
  11886. this._depthCullingState.depthFunc = this._gl.LESS;
  11887. };
  11888. /**
  11889. * Sets the current depth function to LEQUAL
  11890. */
  11891. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11892. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11893. };
  11894. /**
  11895. * Gets a boolean indicating if stencil buffer is enabled
  11896. * @returns the current stencil buffer state
  11897. */
  11898. Engine.prototype.getStencilBuffer = function () {
  11899. return this._stencilState.stencilTest;
  11900. };
  11901. /**
  11902. * Enable or disable the stencil buffer
  11903. * @param enable defines if the stencil buffer must be enabled or disabled
  11904. */
  11905. Engine.prototype.setStencilBuffer = function (enable) {
  11906. this._stencilState.stencilTest = enable;
  11907. };
  11908. /**
  11909. * Gets the current stencil mask
  11910. * @returns a number defining the new stencil mask to use
  11911. */
  11912. Engine.prototype.getStencilMask = function () {
  11913. return this._stencilState.stencilMask;
  11914. };
  11915. /**
  11916. * Sets the current stencil mask
  11917. * @param mask defines the new stencil mask to use
  11918. */
  11919. Engine.prototype.setStencilMask = function (mask) {
  11920. this._stencilState.stencilMask = mask;
  11921. };
  11922. /**
  11923. * Gets the current stencil function
  11924. * @returns a number defining the stencil function to use
  11925. */
  11926. Engine.prototype.getStencilFunction = function () {
  11927. return this._stencilState.stencilFunc;
  11928. };
  11929. /**
  11930. * Gets the current stencil reference value
  11931. * @returns a number defining the stencil reference value to use
  11932. */
  11933. Engine.prototype.getStencilFunctionReference = function () {
  11934. return this._stencilState.stencilFuncRef;
  11935. };
  11936. /**
  11937. * Gets the current stencil mask
  11938. * @returns a number defining the stencil mask to use
  11939. */
  11940. Engine.prototype.getStencilFunctionMask = function () {
  11941. return this._stencilState.stencilFuncMask;
  11942. };
  11943. /**
  11944. * Sets the current stencil function
  11945. * @param stencilFunc defines the new stencil function to use
  11946. */
  11947. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11948. this._stencilState.stencilFunc = stencilFunc;
  11949. };
  11950. /**
  11951. * Sets the current stencil reference
  11952. * @param reference defines the new stencil reference to use
  11953. */
  11954. Engine.prototype.setStencilFunctionReference = function (reference) {
  11955. this._stencilState.stencilFuncRef = reference;
  11956. };
  11957. /**
  11958. * Sets the current stencil mask
  11959. * @param mask defines the new stencil mask to use
  11960. */
  11961. Engine.prototype.setStencilFunctionMask = function (mask) {
  11962. this._stencilState.stencilFuncMask = mask;
  11963. };
  11964. /**
  11965. * Gets the current stencil operation when stencil fails
  11966. * @returns a number defining stencil operation to use when stencil fails
  11967. */
  11968. Engine.prototype.getStencilOperationFail = function () {
  11969. return this._stencilState.stencilOpStencilFail;
  11970. };
  11971. /**
  11972. * Gets the current stencil operation when depth fails
  11973. * @returns a number defining stencil operation to use when depth fails
  11974. */
  11975. Engine.prototype.getStencilOperationDepthFail = function () {
  11976. return this._stencilState.stencilOpDepthFail;
  11977. };
  11978. /**
  11979. * Gets the current stencil operation when stencil passes
  11980. * @returns a number defining stencil operation to use when stencil passes
  11981. */
  11982. Engine.prototype.getStencilOperationPass = function () {
  11983. return this._stencilState.stencilOpStencilDepthPass;
  11984. };
  11985. /**
  11986. * Sets the stencil operation to use when stencil fails
  11987. * @param operation defines the stencil operation to use when stencil fails
  11988. */
  11989. Engine.prototype.setStencilOperationFail = function (operation) {
  11990. this._stencilState.stencilOpStencilFail = operation;
  11991. };
  11992. /**
  11993. * Sets the stencil operation to use when depth fails
  11994. * @param operation defines the stencil operation to use when depth fails
  11995. */
  11996. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11997. this._stencilState.stencilOpDepthFail = operation;
  11998. };
  11999. /**
  12000. * Sets the stencil operation to use when stencil passes
  12001. * @param operation defines the stencil operation to use when stencil passes
  12002. */
  12003. Engine.prototype.setStencilOperationPass = function (operation) {
  12004. this._stencilState.stencilOpStencilDepthPass = operation;
  12005. };
  12006. /**
  12007. * Sets a boolean indicating if the dithering state is enabled or disabled
  12008. * @param value defines the dithering state
  12009. */
  12010. Engine.prototype.setDitheringState = function (value) {
  12011. if (value) {
  12012. this._gl.enable(this._gl.DITHER);
  12013. }
  12014. else {
  12015. this._gl.disable(this._gl.DITHER);
  12016. }
  12017. };
  12018. /**
  12019. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12020. * @param value defines the rasterizer state
  12021. */
  12022. Engine.prototype.setRasterizerState = function (value) {
  12023. if (value) {
  12024. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12025. }
  12026. else {
  12027. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12028. }
  12029. };
  12030. /**
  12031. * stop executing a render loop function and remove it from the execution array
  12032. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12033. */
  12034. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12035. if (!renderFunction) {
  12036. this._activeRenderLoops = [];
  12037. return;
  12038. }
  12039. var index = this._activeRenderLoops.indexOf(renderFunction);
  12040. if (index >= 0) {
  12041. this._activeRenderLoops.splice(index, 1);
  12042. }
  12043. };
  12044. /** @ignore */
  12045. Engine.prototype._renderLoop = function () {
  12046. if (!this._contextWasLost) {
  12047. var shouldRender = true;
  12048. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12049. shouldRender = false;
  12050. }
  12051. if (shouldRender) {
  12052. // Start new frame
  12053. this.beginFrame();
  12054. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12055. var renderFunction = this._activeRenderLoops[index];
  12056. renderFunction();
  12057. }
  12058. // Present
  12059. this.endFrame();
  12060. }
  12061. }
  12062. if (this._activeRenderLoops.length > 0) {
  12063. // Register new frame
  12064. var requester = null;
  12065. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12066. requester = this._vrDisplay;
  12067. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12068. }
  12069. else {
  12070. this._renderingQueueLaunched = false;
  12071. }
  12072. };
  12073. /**
  12074. * Register and execute a render loop. The engine can have more than one render function
  12075. * @param renderFunction defines the function to continuously execute
  12076. */
  12077. Engine.prototype.runRenderLoop = function (renderFunction) {
  12078. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12079. return;
  12080. }
  12081. this._activeRenderLoops.push(renderFunction);
  12082. if (!this._renderingQueueLaunched) {
  12083. this._renderingQueueLaunched = true;
  12084. this._bindedRenderFunction = this._renderLoop.bind(this);
  12085. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12086. }
  12087. };
  12088. /**
  12089. * Toggle full screen mode
  12090. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12091. * @param options defines an option object to be sent to the requestFullscreen function
  12092. */
  12093. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12094. if (this.isFullscreen) {
  12095. BABYLON.Tools.ExitFullscreen();
  12096. }
  12097. else {
  12098. this._pointerLockRequested = requestPointerLock;
  12099. if (this._renderingCanvas) {
  12100. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12101. }
  12102. }
  12103. };
  12104. /**
  12105. * Clear the current render buffer or the current render target (if any is set up)
  12106. * @param color defines the color to use
  12107. * @param backBuffer defines if the back buffer must be cleared
  12108. * @param depth defines if the depth buffer must be cleared
  12109. * @param stencil defines if the stencil buffer must be cleared
  12110. */
  12111. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12112. if (stencil === void 0) { stencil = false; }
  12113. this.applyStates();
  12114. var mode = 0;
  12115. if (backBuffer && color) {
  12116. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12117. mode |= this._gl.COLOR_BUFFER_BIT;
  12118. }
  12119. if (depth) {
  12120. this._gl.clearDepth(1.0);
  12121. mode |= this._gl.DEPTH_BUFFER_BIT;
  12122. }
  12123. if (stencil) {
  12124. this._gl.clearStencil(0);
  12125. mode |= this._gl.STENCIL_BUFFER_BIT;
  12126. }
  12127. this._gl.clear(mode);
  12128. };
  12129. /**
  12130. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12131. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12132. * @param y defines the y-coordinate of the corner of the clear rectangle
  12133. * @param width defines the width of the clear rectangle
  12134. * @param height defines the height of the clear rectangle
  12135. * @param clearColor defines the clear color
  12136. */
  12137. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12138. var gl = this._gl;
  12139. // Save state
  12140. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12141. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12142. // Change state
  12143. gl.enable(gl.SCISSOR_TEST);
  12144. gl.scissor(x, y, width, height);
  12145. // Clear
  12146. this.clear(clearColor, true, true, true);
  12147. // Restore state
  12148. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12149. if (curScissor === true) {
  12150. gl.enable(gl.SCISSOR_TEST);
  12151. }
  12152. else {
  12153. gl.disable(gl.SCISSOR_TEST);
  12154. }
  12155. };
  12156. /**
  12157. * Set the WebGL's viewport
  12158. * @param viewport defines the viewport element to be used
  12159. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12160. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12161. */
  12162. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12163. var width = requiredWidth || this.getRenderWidth();
  12164. var height = requiredHeight || this.getRenderHeight();
  12165. var x = viewport.x || 0;
  12166. var y = viewport.y || 0;
  12167. this._cachedViewport = viewport;
  12168. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12169. };
  12170. /**
  12171. * Directly set the WebGL Viewport
  12172. * @param x defines the x coordinate of the viewport (in screen space)
  12173. * @param y defines the y coordinate of the viewport (in screen space)
  12174. * @param width defines the width of the viewport (in screen space)
  12175. * @param height defines the height of the viewport (in screen space)
  12176. * @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
  12177. */
  12178. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12179. var currentViewport = this._cachedViewport;
  12180. this._cachedViewport = null;
  12181. this._gl.viewport(x, y, width, height);
  12182. return currentViewport;
  12183. };
  12184. /**
  12185. * Begin a new frame
  12186. */
  12187. Engine.prototype.beginFrame = function () {
  12188. this.onBeginFrameObservable.notifyObservers(this);
  12189. this._measureFps();
  12190. };
  12191. /**
  12192. * Enf the current frame
  12193. */
  12194. Engine.prototype.endFrame = function () {
  12195. // Force a flush in case we are using a bad OS.
  12196. if (this._badOS) {
  12197. this.flushFramebuffer();
  12198. }
  12199. // Submit frame to the vr device, if enabled
  12200. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12201. // TODO: We should only submit the frame if we read frameData successfully.
  12202. this._vrDisplay.submitFrame();
  12203. }
  12204. this.onEndFrameObservable.notifyObservers(this);
  12205. };
  12206. /**
  12207. * Resize the view according to the canvas' size
  12208. */
  12209. Engine.prototype.resize = function () {
  12210. // We're not resizing the size of the canvas while in VR mode & presenting
  12211. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12212. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12213. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12214. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12215. }
  12216. };
  12217. /**
  12218. * Force a specific size of the canvas
  12219. * @param width defines the new canvas' width
  12220. * @param height defines the new canvas' height
  12221. */
  12222. Engine.prototype.setSize = function (width, height) {
  12223. if (!this._renderingCanvas) {
  12224. return;
  12225. }
  12226. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12227. return;
  12228. }
  12229. this._renderingCanvas.width = width;
  12230. this._renderingCanvas.height = height;
  12231. for (var index = 0; index < this.scenes.length; index++) {
  12232. var scene = this.scenes[index];
  12233. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12234. var cam = scene.cameras[camIndex];
  12235. cam._currentRenderId = 0;
  12236. }
  12237. }
  12238. if (this.onResizeObservable.hasObservers) {
  12239. this.onResizeObservable.notifyObservers(this);
  12240. }
  12241. };
  12242. // WebVR functions
  12243. /**
  12244. * Gets a boolean indicating if a webVR device was detected
  12245. * @returns true if a webVR device was detected
  12246. */
  12247. Engine.prototype.isVRDevicePresent = function () {
  12248. return !!this._vrDisplay;
  12249. };
  12250. /**
  12251. * Gets the current webVR device
  12252. * @returns the current webVR device (or null)
  12253. */
  12254. Engine.prototype.getVRDevice = function () {
  12255. return this._vrDisplay;
  12256. };
  12257. /**
  12258. * Initializes a webVR display and starts listening to display change events
  12259. * The onVRDisplayChangedObservable will be notified upon these changes
  12260. * @returns The onVRDisplayChangedObservable
  12261. */
  12262. Engine.prototype.initWebVR = function () {
  12263. this.initWebVRAsync();
  12264. return this.onVRDisplayChangedObservable;
  12265. };
  12266. /**
  12267. * Initializes a webVR display and starts listening to display change events
  12268. * The onVRDisplayChangedObservable will be notified upon these changes
  12269. * @returns A promise containing a VRDisplay and if vr is supported
  12270. */
  12271. Engine.prototype.initWebVRAsync = function () {
  12272. var _this = this;
  12273. var notifyObservers = function () {
  12274. var eventArgs = {
  12275. vrDisplay: _this._vrDisplay,
  12276. vrSupported: _this._vrSupported
  12277. };
  12278. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12279. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12280. };
  12281. if (!this._onVrDisplayConnect) {
  12282. this._onVrDisplayConnect = function (event) {
  12283. _this._vrDisplay = event.display;
  12284. notifyObservers();
  12285. };
  12286. this._onVrDisplayDisconnect = function () {
  12287. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12288. _this._vrDisplay = undefined;
  12289. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12290. notifyObservers();
  12291. };
  12292. this._onVrDisplayPresentChange = function () {
  12293. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12294. };
  12295. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12296. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12297. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12298. }
  12299. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12300. this._webVRInitPromise.then(notifyObservers);
  12301. return this._webVRInitPromise;
  12302. };
  12303. /**
  12304. * Call this function to switch to webVR mode
  12305. * Will do nothing if webVR is not supported or if there is no webVR device
  12306. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12307. */
  12308. Engine.prototype.enableVR = function () {
  12309. var _this = this;
  12310. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12311. var onResolved = function () {
  12312. _this.onVRRequestPresentComplete.notifyObservers(true);
  12313. _this._onVRFullScreenTriggered();
  12314. };
  12315. var onRejected = function () {
  12316. _this.onVRRequestPresentComplete.notifyObservers(false);
  12317. };
  12318. this.onVRRequestPresentStart.notifyObservers(this);
  12319. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12320. }
  12321. };
  12322. /**
  12323. * Call this function to leave webVR mode
  12324. * Will do nothing if webVR is not supported or if there is no webVR device
  12325. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12326. */
  12327. Engine.prototype.disableVR = function () {
  12328. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12329. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12330. }
  12331. };
  12332. Engine.prototype._getVRDisplaysAsync = function () {
  12333. var _this = this;
  12334. return new Promise(function (res, rej) {
  12335. if (navigator.getVRDisplays) {
  12336. navigator.getVRDisplays().then(function (devices) {
  12337. _this._vrSupported = true;
  12338. // note that devices may actually be an empty array. This is fine;
  12339. // we expect this._vrDisplay to be undefined in this case.
  12340. _this._vrDisplay = devices[0];
  12341. res({
  12342. vrDisplay: _this._vrDisplay,
  12343. vrSupported: _this._vrSupported
  12344. });
  12345. });
  12346. }
  12347. else {
  12348. _this._vrDisplay = undefined;
  12349. _this._vrSupported = false;
  12350. res({
  12351. vrDisplay: _this._vrDisplay,
  12352. vrSupported: _this._vrSupported
  12353. });
  12354. }
  12355. });
  12356. };
  12357. /**
  12358. * Binds the frame buffer to the specified texture.
  12359. * @param texture The texture to render to or null for the default canvas
  12360. * @param faceIndex The face of the texture to render to in case of cube texture
  12361. * @param requiredWidth The width of the target to render to
  12362. * @param requiredHeight The height of the target to render to
  12363. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12364. * @param depthStencilTexture The depth stencil texture to use to render
  12365. */
  12366. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  12367. if (this._currentRenderTarget) {
  12368. this.unBindFramebuffer(this._currentRenderTarget);
  12369. }
  12370. this._currentRenderTarget = texture;
  12371. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12372. var gl = this._gl;
  12373. if (texture.isCube) {
  12374. if (faceIndex === undefined) {
  12375. faceIndex = 0;
  12376. }
  12377. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  12378. if (depthStencilTexture) {
  12379. if (depthStencilTexture._generateStencilBuffer) {
  12380. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12381. }
  12382. else {
  12383. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12384. }
  12385. }
  12386. }
  12387. if (this._cachedViewport && !forceFullscreenViewport) {
  12388. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12389. }
  12390. else {
  12391. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  12392. }
  12393. this.wipeCaches();
  12394. };
  12395. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12396. if (this._currentFramebuffer !== framebuffer) {
  12397. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12398. this._currentFramebuffer = framebuffer;
  12399. }
  12400. };
  12401. /**
  12402. * Unbind the current render target texture from the webGL context
  12403. * @param texture defines the render target texture to unbind
  12404. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12405. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12406. */
  12407. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12408. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12409. this._currentRenderTarget = null;
  12410. // If MSAA, we need to bitblt back to main texture
  12411. var gl = this._gl;
  12412. if (texture._MSAAFramebuffer) {
  12413. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12414. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12415. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12416. }
  12417. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12418. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12419. gl.generateMipmap(gl.TEXTURE_2D);
  12420. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12421. }
  12422. if (onBeforeUnbind) {
  12423. if (texture._MSAAFramebuffer) {
  12424. // Bind the correct framebuffer
  12425. this.bindUnboundFramebuffer(texture._framebuffer);
  12426. }
  12427. onBeforeUnbind();
  12428. }
  12429. this.bindUnboundFramebuffer(null);
  12430. };
  12431. /**
  12432. * Unbind a list of render target textures from the webGL context
  12433. * This is used only when drawBuffer extension or webGL2 are active
  12434. * @param textures defines the render target textures to unbind
  12435. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12436. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12437. */
  12438. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12439. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12440. this._currentRenderTarget = null;
  12441. // If MSAA, we need to bitblt back to main texture
  12442. var gl = this._gl;
  12443. if (textures[0]._MSAAFramebuffer) {
  12444. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12445. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12446. var attachments = textures[0]._attachments;
  12447. if (!attachments) {
  12448. attachments = new Array(textures.length);
  12449. textures[0]._attachments = attachments;
  12450. }
  12451. for (var i = 0; i < textures.length; i++) {
  12452. var texture = textures[i];
  12453. for (var j = 0; j < attachments.length; j++) {
  12454. attachments[j] = gl.NONE;
  12455. }
  12456. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12457. gl.readBuffer(attachments[i]);
  12458. gl.drawBuffers(attachments);
  12459. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12460. }
  12461. for (var i = 0; i < attachments.length; i++) {
  12462. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12463. }
  12464. gl.drawBuffers(attachments);
  12465. }
  12466. for (var i = 0; i < textures.length; i++) {
  12467. var texture = textures[i];
  12468. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12469. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12470. gl.generateMipmap(gl.TEXTURE_2D);
  12471. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12472. }
  12473. }
  12474. if (onBeforeUnbind) {
  12475. if (textures[0]._MSAAFramebuffer) {
  12476. // Bind the correct framebuffer
  12477. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12478. }
  12479. onBeforeUnbind();
  12480. }
  12481. this.bindUnboundFramebuffer(null);
  12482. };
  12483. /**
  12484. * Force the mipmap generation for the given render target texture
  12485. * @param texture defines the render target texture to use
  12486. */
  12487. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12488. if (texture.generateMipMaps) {
  12489. var gl = this._gl;
  12490. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12491. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12492. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12493. }
  12494. };
  12495. /**
  12496. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  12497. */
  12498. Engine.prototype.flushFramebuffer = function () {
  12499. this._gl.flush();
  12500. };
  12501. /**
  12502. * Unbind the current render target and bind the default framebuffer
  12503. */
  12504. Engine.prototype.restoreDefaultFramebuffer = function () {
  12505. if (this._currentRenderTarget) {
  12506. this.unBindFramebuffer(this._currentRenderTarget);
  12507. }
  12508. else {
  12509. this.bindUnboundFramebuffer(null);
  12510. }
  12511. if (this._cachedViewport) {
  12512. this.setViewport(this._cachedViewport);
  12513. }
  12514. this.wipeCaches();
  12515. };
  12516. // UBOs
  12517. /**
  12518. * Create an uniform buffer
  12519. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12520. * @param elements defines the content of the uniform buffer
  12521. * @returns the webGL uniform buffer
  12522. */
  12523. Engine.prototype.createUniformBuffer = function (elements) {
  12524. var ubo = this._gl.createBuffer();
  12525. if (!ubo) {
  12526. throw new Error("Unable to create uniform buffer");
  12527. }
  12528. this.bindUniformBuffer(ubo);
  12529. if (elements instanceof Float32Array) {
  12530. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12531. }
  12532. else {
  12533. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12534. }
  12535. this.bindUniformBuffer(null);
  12536. ubo.references = 1;
  12537. return ubo;
  12538. };
  12539. /**
  12540. * Create a dynamic uniform buffer
  12541. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12542. * @param elements defines the content of the uniform buffer
  12543. * @returns the webGL uniform buffer
  12544. */
  12545. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12546. var ubo = this._gl.createBuffer();
  12547. if (!ubo) {
  12548. throw new Error("Unable to create dynamic uniform buffer");
  12549. }
  12550. this.bindUniformBuffer(ubo);
  12551. if (elements instanceof Float32Array) {
  12552. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12553. }
  12554. else {
  12555. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12556. }
  12557. this.bindUniformBuffer(null);
  12558. ubo.references = 1;
  12559. return ubo;
  12560. };
  12561. /**
  12562. * Update an existing uniform buffer
  12563. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12564. * @param uniformBuffer defines the target uniform buffer
  12565. * @param elements defines the content to update
  12566. * @param offset defines the offset in the uniform buffer where update should start
  12567. * @param count defines the size of the data to update
  12568. */
  12569. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12570. this.bindUniformBuffer(uniformBuffer);
  12571. if (offset === undefined) {
  12572. offset = 0;
  12573. }
  12574. if (count === undefined) {
  12575. if (elements instanceof Float32Array) {
  12576. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12577. }
  12578. else {
  12579. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12580. }
  12581. }
  12582. else {
  12583. if (elements instanceof Float32Array) {
  12584. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12585. }
  12586. else {
  12587. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12588. }
  12589. }
  12590. this.bindUniformBuffer(null);
  12591. };
  12592. // VBOs
  12593. Engine.prototype._resetVertexBufferBinding = function () {
  12594. this.bindArrayBuffer(null);
  12595. this._cachedVertexBuffers = null;
  12596. };
  12597. /**
  12598. * Creates a vertex buffer
  12599. * @param data the data for the vertex buffer
  12600. * @returns the new WebGL static buffer
  12601. */
  12602. Engine.prototype.createVertexBuffer = function (data) {
  12603. var vbo = this._gl.createBuffer();
  12604. if (!vbo) {
  12605. throw new Error("Unable to create vertex buffer");
  12606. }
  12607. this.bindArrayBuffer(vbo);
  12608. if (data instanceof Array) {
  12609. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  12610. }
  12611. else {
  12612. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  12613. }
  12614. this._resetVertexBufferBinding();
  12615. vbo.references = 1;
  12616. return vbo;
  12617. };
  12618. /**
  12619. * Creates a dynamic vertex buffer
  12620. * @param data the data for the dynamic vertex buffer
  12621. * @returns the new WebGL dynamic buffer
  12622. */
  12623. Engine.prototype.createDynamicVertexBuffer = function (data) {
  12624. var vbo = this._gl.createBuffer();
  12625. if (!vbo) {
  12626. throw new Error("Unable to create dynamic vertex buffer");
  12627. }
  12628. this.bindArrayBuffer(vbo);
  12629. if (data instanceof Array) {
  12630. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  12631. }
  12632. else {
  12633. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  12634. }
  12635. this._resetVertexBufferBinding();
  12636. vbo.references = 1;
  12637. return vbo;
  12638. };
  12639. /**
  12640. * Update a dynamic index buffer
  12641. * @param indexBuffer defines the target index buffer
  12642. * @param indices defines the data to update
  12643. * @param offset defines the offset in the target index buffer where update should start
  12644. */
  12645. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  12646. if (offset === void 0) { offset = 0; }
  12647. // Force cache update
  12648. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  12649. this.bindIndexBuffer(indexBuffer);
  12650. var arrayBuffer;
  12651. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  12652. arrayBuffer = indices;
  12653. }
  12654. else {
  12655. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12656. }
  12657. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12658. this._resetIndexBufferBinding();
  12659. };
  12660. /**
  12661. * Updates a dynamic vertex buffer.
  12662. * @param vertexBuffer the vertex buffer to update
  12663. * @param data the data used to update the vertex buffer
  12664. * @param byteOffset the byte offset of the data
  12665. * @param byteLength the byte length of the data
  12666. */
  12667. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  12668. this.bindArrayBuffer(vertexBuffer);
  12669. if (byteOffset === undefined) {
  12670. byteOffset = 0;
  12671. }
  12672. if (byteLength === undefined) {
  12673. if (data instanceof Array) {
  12674. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  12675. }
  12676. else {
  12677. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  12678. }
  12679. }
  12680. else {
  12681. if (data instanceof Array) {
  12682. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  12683. }
  12684. else {
  12685. if (data instanceof ArrayBuffer) {
  12686. data = new Uint8Array(data, byteOffset, byteLength);
  12687. }
  12688. else {
  12689. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  12690. }
  12691. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12692. }
  12693. }
  12694. this._resetVertexBufferBinding();
  12695. };
  12696. Engine.prototype._resetIndexBufferBinding = function () {
  12697. this.bindIndexBuffer(null);
  12698. this._cachedIndexBuffer = null;
  12699. };
  12700. /**
  12701. * Creates a new index buffer
  12702. * @param indices defines the content of the index buffer
  12703. * @param updatable defines if the index buffer must be updatable
  12704. * @returns a new webGL buffer
  12705. */
  12706. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  12707. var vbo = this._gl.createBuffer();
  12708. if (!vbo) {
  12709. throw new Error("Unable to create index buffer");
  12710. }
  12711. this.bindIndexBuffer(vbo);
  12712. // Check for 32 bits indices
  12713. var arrayBuffer;
  12714. var need32Bits = false;
  12715. if (indices instanceof Uint16Array) {
  12716. arrayBuffer = indices;
  12717. }
  12718. else {
  12719. //check 32 bit support
  12720. if (this._caps.uintIndices) {
  12721. if (indices instanceof Uint32Array) {
  12722. arrayBuffer = indices;
  12723. need32Bits = true;
  12724. }
  12725. else {
  12726. //number[] or Int32Array, check if 32 bit is necessary
  12727. for (var index = 0; index < indices.length; index++) {
  12728. if (indices[index] > 65535) {
  12729. need32Bits = true;
  12730. break;
  12731. }
  12732. }
  12733. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12734. }
  12735. }
  12736. else {
  12737. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  12738. arrayBuffer = new Uint16Array(indices);
  12739. }
  12740. }
  12741. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  12742. this._resetIndexBufferBinding();
  12743. vbo.references = 1;
  12744. vbo.is32Bits = need32Bits;
  12745. return vbo;
  12746. };
  12747. /**
  12748. * Bind a webGL buffer to the webGL context
  12749. * @param buffer defines the buffer to bind
  12750. */
  12751. Engine.prototype.bindArrayBuffer = function (buffer) {
  12752. if (!this._vaoRecordInProgress) {
  12753. this._unbindVertexArrayObject();
  12754. }
  12755. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  12756. };
  12757. /**
  12758. * Bind an uniform buffer to the current webGL context
  12759. * @param buffer defines the buffer to bind
  12760. */
  12761. Engine.prototype.bindUniformBuffer = function (buffer) {
  12762. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  12763. };
  12764. /**
  12765. * Bind a buffer to the current webGL context at a given location
  12766. * @param buffer defines the buffer to bind
  12767. * @param location defines the index where to bind the buffer
  12768. */
  12769. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  12770. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  12771. };
  12772. /**
  12773. * Bind a specific block at a given index in a specific shader program
  12774. * @param shaderProgram defines the shader program
  12775. * @param blockName defines the block name
  12776. * @param index defines the index where to bind the block
  12777. */
  12778. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  12779. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  12780. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  12781. };
  12782. ;
  12783. Engine.prototype.bindIndexBuffer = function (buffer) {
  12784. if (!this._vaoRecordInProgress) {
  12785. this._unbindVertexArrayObject();
  12786. }
  12787. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  12788. };
  12789. Engine.prototype.bindBuffer = function (buffer, target) {
  12790. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  12791. this._gl.bindBuffer(target, buffer);
  12792. this._currentBoundBuffer[target] = buffer;
  12793. }
  12794. };
  12795. /**
  12796. * update the bound buffer with the given data
  12797. * @param data defines the data to update
  12798. */
  12799. Engine.prototype.updateArrayBuffer = function (data) {
  12800. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12801. };
  12802. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  12803. var pointer = this._currentBufferPointers[indx];
  12804. var changed = false;
  12805. if (!pointer.active) {
  12806. changed = true;
  12807. pointer.active = true;
  12808. pointer.index = indx;
  12809. pointer.size = size;
  12810. pointer.type = type;
  12811. pointer.normalized = normalized;
  12812. pointer.stride = stride;
  12813. pointer.offset = offset;
  12814. pointer.buffer = buffer;
  12815. }
  12816. else {
  12817. if (pointer.buffer !== buffer) {
  12818. pointer.buffer = buffer;
  12819. changed = true;
  12820. }
  12821. if (pointer.size !== size) {
  12822. pointer.size = size;
  12823. changed = true;
  12824. }
  12825. if (pointer.type !== type) {
  12826. pointer.type = type;
  12827. changed = true;
  12828. }
  12829. if (pointer.normalized !== normalized) {
  12830. pointer.normalized = normalized;
  12831. changed = true;
  12832. }
  12833. if (pointer.stride !== stride) {
  12834. pointer.stride = stride;
  12835. changed = true;
  12836. }
  12837. if (pointer.offset !== offset) {
  12838. pointer.offset = offset;
  12839. changed = true;
  12840. }
  12841. }
  12842. if (changed || this._vaoRecordInProgress) {
  12843. this.bindArrayBuffer(buffer);
  12844. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  12845. }
  12846. };
  12847. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  12848. if (indexBuffer == null) {
  12849. return;
  12850. }
  12851. if (this._cachedIndexBuffer !== indexBuffer) {
  12852. this._cachedIndexBuffer = indexBuffer;
  12853. this.bindIndexBuffer(indexBuffer);
  12854. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  12855. }
  12856. };
  12857. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  12858. var attributes = effect.getAttributesNames();
  12859. if (!this._vaoRecordInProgress) {
  12860. this._unbindVertexArrayObject();
  12861. }
  12862. this.unbindAllAttributes();
  12863. for (var index = 0; index < attributes.length; index++) {
  12864. var order = effect.getAttributeLocation(index);
  12865. if (order >= 0) {
  12866. var vertexBuffer = vertexBuffers[attributes[index]];
  12867. if (!vertexBuffer) {
  12868. continue;
  12869. }
  12870. this._gl.enableVertexAttribArray(order);
  12871. if (!this._vaoRecordInProgress) {
  12872. this._vertexAttribArraysEnabled[order] = true;
  12873. }
  12874. var buffer = vertexBuffer.getBuffer();
  12875. if (buffer) {
  12876. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  12877. if (vertexBuffer.getIsInstanced()) {
  12878. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12879. if (!this._vaoRecordInProgress) {
  12880. this._currentInstanceLocations.push(order);
  12881. this._currentInstanceBuffers.push(buffer);
  12882. }
  12883. }
  12884. }
  12885. }
  12886. }
  12887. };
  12888. /**
  12889. * Records a vertex array object
  12890. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  12891. * @param vertexBuffers defines the list of vertex buffers to store
  12892. * @param indexBuffer defines the index buffer to store
  12893. * @param effect defines the effect to store
  12894. * @returns the new vertex array object
  12895. */
  12896. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12897. var vao = this._gl.createVertexArray();
  12898. this._vaoRecordInProgress = true;
  12899. this._gl.bindVertexArray(vao);
  12900. this._mustWipeVertexAttributes = true;
  12901. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12902. this.bindIndexBuffer(indexBuffer);
  12903. this._vaoRecordInProgress = false;
  12904. this._gl.bindVertexArray(null);
  12905. return vao;
  12906. };
  12907. /**
  12908. * Bind a specific vertex array object
  12909. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  12910. * @param vertexArrayObject defines the vertex array object to bind
  12911. * @param indexBuffer defines the index buffer to bind
  12912. */
  12913. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12914. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12915. this._cachedVertexArrayObject = vertexArrayObject;
  12916. this._gl.bindVertexArray(vertexArrayObject);
  12917. this._cachedVertexBuffers = null;
  12918. this._cachedIndexBuffer = null;
  12919. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12920. this._mustWipeVertexAttributes = true;
  12921. }
  12922. };
  12923. /**
  12924. * Bind webGl buffers directly to the webGL context
  12925. * @param vertexBuffer defines the vertex buffer to bind
  12926. * @param indexBuffer defines the index buffer to bind
  12927. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  12928. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  12929. * @param effect defines the effect associated with the vertex buffer
  12930. */
  12931. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12932. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12933. this._cachedVertexBuffers = vertexBuffer;
  12934. this._cachedEffectForVertexBuffers = effect;
  12935. var attributesCount = effect.getAttributesCount();
  12936. this._unbindVertexArrayObject();
  12937. this.unbindAllAttributes();
  12938. var offset = 0;
  12939. for (var index = 0; index < attributesCount; index++) {
  12940. if (index < vertexDeclaration.length) {
  12941. var order = effect.getAttributeLocation(index);
  12942. if (order >= 0) {
  12943. this._gl.enableVertexAttribArray(order);
  12944. this._vertexAttribArraysEnabled[order] = true;
  12945. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12946. }
  12947. offset += vertexDeclaration[index] * 4;
  12948. }
  12949. }
  12950. }
  12951. this._bindIndexBufferWithCache(indexBuffer);
  12952. };
  12953. Engine.prototype._unbindVertexArrayObject = function () {
  12954. if (!this._cachedVertexArrayObject) {
  12955. return;
  12956. }
  12957. this._cachedVertexArrayObject = null;
  12958. this._gl.bindVertexArray(null);
  12959. };
  12960. /**
  12961. * Bind a list of vertex buffers to the webGL context
  12962. * @param vertexBuffers defines the list of vertex buffers to bind
  12963. * @param indexBuffer defines the index buffer to bind
  12964. * @param effect defines the effect associated with the vertex buffers
  12965. */
  12966. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12967. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12968. this._cachedVertexBuffers = vertexBuffers;
  12969. this._cachedEffectForVertexBuffers = effect;
  12970. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12971. }
  12972. this._bindIndexBufferWithCache(indexBuffer);
  12973. };
  12974. /**
  12975. * Unbind all instance attributes
  12976. */
  12977. Engine.prototype.unbindInstanceAttributes = function () {
  12978. var boundBuffer;
  12979. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12980. var instancesBuffer = this._currentInstanceBuffers[i];
  12981. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12982. boundBuffer = instancesBuffer;
  12983. this.bindArrayBuffer(instancesBuffer);
  12984. }
  12985. var offsetLocation = this._currentInstanceLocations[i];
  12986. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12987. }
  12988. this._currentInstanceBuffers.length = 0;
  12989. this._currentInstanceLocations.length = 0;
  12990. };
  12991. /**
  12992. * Release and free the memory of a vertex array object
  12993. * @param vao defines the vertex array object to delete
  12994. */
  12995. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12996. this._gl.deleteVertexArray(vao);
  12997. };
  12998. /** @ignore */
  12999. Engine.prototype._releaseBuffer = function (buffer) {
  13000. buffer.references--;
  13001. if (buffer.references === 0) {
  13002. this._gl.deleteBuffer(buffer);
  13003. return true;
  13004. }
  13005. return false;
  13006. };
  13007. /**
  13008. * Creates a webGL buffer to use with instanciation
  13009. * @param capacity defines the size of the buffer
  13010. * @returns the webGL buffer
  13011. */
  13012. Engine.prototype.createInstancesBuffer = function (capacity) {
  13013. var buffer = this._gl.createBuffer();
  13014. if (!buffer) {
  13015. throw new Error("Unable to create instance buffer");
  13016. }
  13017. buffer.capacity = capacity;
  13018. this.bindArrayBuffer(buffer);
  13019. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13020. return buffer;
  13021. };
  13022. /**
  13023. * Delete a webGL buffer used with instanciation
  13024. * @param buffer defines the webGL buffer to delete
  13025. */
  13026. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13027. this._gl.deleteBuffer(buffer);
  13028. };
  13029. /**
  13030. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13031. * @param instancesBuffer defines the webGL buffer to update and bind
  13032. * @param data defines the data to store in the buffer
  13033. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13034. */
  13035. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13036. this.bindArrayBuffer(instancesBuffer);
  13037. if (data) {
  13038. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13039. }
  13040. if (offsetLocations[0].index !== undefined) {
  13041. var stride = 0;
  13042. for (var i = 0; i < offsetLocations.length; i++) {
  13043. var ai = offsetLocations[i];
  13044. stride += ai.attributeSize * 4;
  13045. }
  13046. for (var i = 0; i < offsetLocations.length; i++) {
  13047. var ai = offsetLocations[i];
  13048. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13049. this._gl.enableVertexAttribArray(ai.index);
  13050. this._vertexAttribArraysEnabled[ai.index] = true;
  13051. }
  13052. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13053. this._gl.vertexAttribDivisor(ai.index, 1);
  13054. this._currentInstanceLocations.push(ai.index);
  13055. this._currentInstanceBuffers.push(instancesBuffer);
  13056. }
  13057. }
  13058. else {
  13059. for (var index = 0; index < 4; index++) {
  13060. var offsetLocation = offsetLocations[index];
  13061. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13062. this._gl.enableVertexAttribArray(offsetLocation);
  13063. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13064. }
  13065. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13066. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13067. this._currentInstanceLocations.push(offsetLocation);
  13068. this._currentInstanceBuffers.push(instancesBuffer);
  13069. }
  13070. }
  13071. };
  13072. /**
  13073. * Apply all cached states (depth, culling, stencil and alpha)
  13074. */
  13075. Engine.prototype.applyStates = function () {
  13076. this._depthCullingState.apply(this._gl);
  13077. this._stencilState.apply(this._gl);
  13078. this._alphaState.apply(this._gl);
  13079. };
  13080. /**
  13081. * Send a draw order
  13082. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13083. * @param indexStart defines the starting index
  13084. * @param indexCount defines the number of index to draw
  13085. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13086. */
  13087. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13088. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13089. };
  13090. /**
  13091. * Draw a list of points
  13092. * @param verticesStart defines the index of first vertex to draw
  13093. * @param verticesCount defines the count of vertices to draw
  13094. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13095. */
  13096. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13097. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13098. };
  13099. /**
  13100. * Draw a list of unindexed primitives
  13101. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13102. * @param verticesStart defines the index of first vertex to draw
  13103. * @param verticesCount defines the count of vertices to draw
  13104. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13105. */
  13106. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13107. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13108. };
  13109. /**
  13110. * Draw a list of indexed primitives
  13111. * @param fillMode defines the primitive to use
  13112. * @param indexStart defines the starting index
  13113. * @param indexCount defines the number of index to draw
  13114. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13115. */
  13116. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13117. // Apply states
  13118. this.applyStates();
  13119. this._drawCalls.addCount(1, false);
  13120. // Render
  13121. var drawMode = this._drawMode(fillMode);
  13122. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13123. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13124. if (instancesCount) {
  13125. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13126. }
  13127. else {
  13128. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13129. }
  13130. };
  13131. /**
  13132. * Draw a list of unindexed primitives
  13133. * @param fillMode defines the primitive to use
  13134. * @param verticesStart defines the index of first vertex to draw
  13135. * @param verticesCount defines the count of vertices to draw
  13136. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13137. */
  13138. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13139. // Apply states
  13140. this.applyStates();
  13141. this._drawCalls.addCount(1, false);
  13142. var drawMode = this._drawMode(fillMode);
  13143. if (instancesCount) {
  13144. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13145. }
  13146. else {
  13147. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13148. }
  13149. };
  13150. Engine.prototype._drawMode = function (fillMode) {
  13151. switch (fillMode) {
  13152. // Triangle views
  13153. case BABYLON.Material.TriangleFillMode:
  13154. return this._gl.TRIANGLES;
  13155. case BABYLON.Material.PointFillMode:
  13156. return this._gl.POINTS;
  13157. case BABYLON.Material.WireFrameFillMode:
  13158. return this._gl.LINES;
  13159. // Draw modes
  13160. case BABYLON.Material.PointListDrawMode:
  13161. return this._gl.POINTS;
  13162. case BABYLON.Material.LineListDrawMode:
  13163. return this._gl.LINES;
  13164. case BABYLON.Material.LineLoopDrawMode:
  13165. return this._gl.LINE_LOOP;
  13166. case BABYLON.Material.LineStripDrawMode:
  13167. return this._gl.LINE_STRIP;
  13168. case BABYLON.Material.TriangleStripDrawMode:
  13169. return this._gl.TRIANGLE_STRIP;
  13170. case BABYLON.Material.TriangleFanDrawMode:
  13171. return this._gl.TRIANGLE_FAN;
  13172. default:
  13173. return this._gl.TRIANGLES;
  13174. }
  13175. };
  13176. // Shaders
  13177. /** @ignore */
  13178. Engine.prototype._releaseEffect = function (effect) {
  13179. if (this._compiledEffects[effect._key]) {
  13180. delete this._compiledEffects[effect._key];
  13181. this._deleteProgram(effect.getProgram());
  13182. }
  13183. };
  13184. /** @ignore */
  13185. Engine.prototype._deleteProgram = function (program) {
  13186. if (program) {
  13187. program.__SPECTOR_rebuildProgram = null;
  13188. if (program.transformFeedback) {
  13189. this.deleteTransformFeedback(program.transformFeedback);
  13190. program.transformFeedback = null;
  13191. }
  13192. this._gl.deleteProgram(program);
  13193. }
  13194. };
  13195. /**
  13196. * Create a new effect (used to store vertex/fragment shaders)
  13197. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13198. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13199. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13200. * @param samplers defines an array of string used to represent textures
  13201. * @param defines defines the string containing the defines to use to compile the shaders
  13202. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13203. * @param onCompiled defines a function to call when the effect creation is successful
  13204. * @param onError defines a function to call when the effect creation has failed
  13205. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13206. * @returns the new Effect
  13207. */
  13208. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13209. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13210. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13211. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13212. if (this._compiledEffects[name]) {
  13213. var compiledEffect = this._compiledEffects[name];
  13214. if (onCompiled && compiledEffect.isReady()) {
  13215. onCompiled(compiledEffect);
  13216. }
  13217. return compiledEffect;
  13218. }
  13219. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13220. effect._key = name;
  13221. this._compiledEffects[name] = effect;
  13222. return effect;
  13223. };
  13224. /**
  13225. * Create an effect to use with particle systems
  13226. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  13227. * @param uniformsNames defines a list of attribute names
  13228. * @param samplers defines an array of string used to represent textures
  13229. * @param defines defines the string containing the defines to use to compile the shaders
  13230. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13231. * @param onCompiled defines a function to call when the effect creation is successful
  13232. * @param onError defines a function to call when the effect creation has failed
  13233. * @returns the new Effect
  13234. */
  13235. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  13236. if (uniformsNames === void 0) { uniformsNames = []; }
  13237. if (samplers === void 0) { samplers = []; }
  13238. if (defines === void 0) { defines = ""; }
  13239. return this.createEffect({
  13240. vertex: "particles",
  13241. fragmentElement: fragmentName
  13242. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  13243. };
  13244. /**
  13245. * Directly creates a webGL program
  13246. * @param vertexCode defines the vertex shader code to use
  13247. * @param fragmentCode defines the fragment shader code to use
  13248. * @param context defines the webGL context to use (if not set, the current one will be used)
  13249. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13250. * @returns the new webGL program
  13251. */
  13252. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13253. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13254. context = context || this._gl;
  13255. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  13256. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  13257. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13258. };
  13259. /**
  13260. * Creates a webGL program
  13261. * @param vertexCode defines the vertex shader code to use
  13262. * @param fragmentCode defines the fragment shader code to use
  13263. * @param defines defines the string containing the defines to use to compile the shaders
  13264. * @param context defines the webGL context to use (if not set, the current one will be used)
  13265. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13266. * @returns the new webGL program
  13267. */
  13268. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13269. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13270. context = context || this._gl;
  13271. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13272. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13273. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  13274. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  13275. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13276. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13277. return program;
  13278. };
  13279. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13280. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13281. var shaderProgram = context.createProgram();
  13282. if (!shaderProgram) {
  13283. throw new Error("Unable to create program");
  13284. }
  13285. context.attachShader(shaderProgram, vertexShader);
  13286. context.attachShader(shaderProgram, fragmentShader);
  13287. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13288. var transformFeedback = this.createTransformFeedback();
  13289. this.bindTransformFeedback(transformFeedback);
  13290. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13291. shaderProgram.transformFeedback = transformFeedback;
  13292. }
  13293. context.linkProgram(shaderProgram);
  13294. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13295. this.bindTransformFeedback(null);
  13296. }
  13297. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13298. if (!linked) {
  13299. context.validateProgram(shaderProgram);
  13300. var error = context.getProgramInfoLog(shaderProgram);
  13301. if (error) {
  13302. throw new Error(error);
  13303. }
  13304. }
  13305. context.deleteShader(vertexShader);
  13306. context.deleteShader(fragmentShader);
  13307. return shaderProgram;
  13308. };
  13309. /**
  13310. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13311. * @param shaderProgram defines the webGL program to use
  13312. * @param uniformsNames defines the list of uniform names
  13313. * @returns an array of webGL uniform locations
  13314. */
  13315. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13316. var results = new Array();
  13317. for (var index = 0; index < uniformsNames.length; index++) {
  13318. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13319. }
  13320. return results;
  13321. };
  13322. /**
  13323. * Gets the lsit of active attributes for a given webGL program
  13324. * @param shaderProgram defines the webGL program to use
  13325. * @param attributesNames defines the list of attribute names to get
  13326. * @returns an array of indices indicating the offset of each attribute
  13327. */
  13328. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13329. var results = [];
  13330. for (var index = 0; index < attributesNames.length; index++) {
  13331. try {
  13332. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13333. }
  13334. catch (e) {
  13335. results.push(-1);
  13336. }
  13337. }
  13338. return results;
  13339. };
  13340. /**
  13341. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13342. * @param effect defines the effect to activate
  13343. */
  13344. Engine.prototype.enableEffect = function (effect) {
  13345. if (!effect) {
  13346. return;
  13347. }
  13348. // Use program
  13349. this.bindSamplers(effect);
  13350. this._currentEffect = effect;
  13351. if (effect.onBind) {
  13352. effect.onBind(effect);
  13353. }
  13354. effect.onBindObservable.notifyObservers(effect);
  13355. };
  13356. /**
  13357. * Set the value of an uniform to an array of int32
  13358. * @param uniform defines the webGL uniform location where to store the value
  13359. * @param array defines the array of int32 to store
  13360. */
  13361. Engine.prototype.setIntArray = function (uniform, array) {
  13362. if (!uniform)
  13363. return;
  13364. this._gl.uniform1iv(uniform, array);
  13365. };
  13366. /**
  13367. * Set the value of an uniform to an array of int32 (stored as vec2)
  13368. * @param uniform defines the webGL uniform location where to store the value
  13369. * @param array defines the array of int32 to store
  13370. */
  13371. Engine.prototype.setIntArray2 = function (uniform, array) {
  13372. if (!uniform || array.length % 2 !== 0)
  13373. return;
  13374. this._gl.uniform2iv(uniform, array);
  13375. };
  13376. /**
  13377. * Set the value of an uniform to an array of int32 (stored as vec3)
  13378. * @param uniform defines the webGL uniform location where to store the value
  13379. * @param array defines the array of int32 to store
  13380. */
  13381. Engine.prototype.setIntArray3 = function (uniform, array) {
  13382. if (!uniform || array.length % 3 !== 0)
  13383. return;
  13384. this._gl.uniform3iv(uniform, array);
  13385. };
  13386. /**
  13387. * Set the value of an uniform to an array of int32 (stored as vec4)
  13388. * @param uniform defines the webGL uniform location where to store the value
  13389. * @param array defines the array of int32 to store
  13390. */
  13391. Engine.prototype.setIntArray4 = function (uniform, array) {
  13392. if (!uniform || array.length % 4 !== 0)
  13393. return;
  13394. this._gl.uniform4iv(uniform, array);
  13395. };
  13396. /**
  13397. * Set the value of an uniform to an array of float32
  13398. * @param uniform defines the webGL uniform location where to store the value
  13399. * @param array defines the array of float32 to store
  13400. */
  13401. Engine.prototype.setFloatArray = function (uniform, array) {
  13402. if (!uniform)
  13403. return;
  13404. this._gl.uniform1fv(uniform, array);
  13405. };
  13406. /**
  13407. * Set the value of an uniform to an array of float32 (stored as vec2)
  13408. * @param uniform defines the webGL uniform location where to store the value
  13409. * @param array defines the array of float32 to store
  13410. */
  13411. Engine.prototype.setFloatArray2 = function (uniform, array) {
  13412. if (!uniform || array.length % 2 !== 0)
  13413. return;
  13414. this._gl.uniform2fv(uniform, array);
  13415. };
  13416. /**
  13417. * Set the value of an uniform to an array of float32 (stored as vec3)
  13418. * @param uniform defines the webGL uniform location where to store the value
  13419. * @param array defines the array of float32 to store
  13420. */
  13421. Engine.prototype.setFloatArray3 = function (uniform, array) {
  13422. if (!uniform || array.length % 3 !== 0)
  13423. return;
  13424. this._gl.uniform3fv(uniform, array);
  13425. };
  13426. /**
  13427. * Set the value of an uniform to an array of float32 (stored as vec4)
  13428. * @param uniform defines the webGL uniform location where to store the value
  13429. * @param array defines the array of float32 to store
  13430. */
  13431. Engine.prototype.setFloatArray4 = function (uniform, array) {
  13432. if (!uniform || array.length % 4 !== 0)
  13433. return;
  13434. this._gl.uniform4fv(uniform, array);
  13435. };
  13436. /**
  13437. * Set the value of an uniform to an array of number
  13438. * @param uniform defines the webGL uniform location where to store the value
  13439. * @param array defines the array of number to store
  13440. */
  13441. Engine.prototype.setArray = function (uniform, array) {
  13442. if (!uniform)
  13443. return;
  13444. this._gl.uniform1fv(uniform, array);
  13445. };
  13446. /**
  13447. * Set the value of an uniform to an array of number (stored as vec2)
  13448. * @param uniform defines the webGL uniform location where to store the value
  13449. * @param array defines the array of number to store
  13450. */
  13451. Engine.prototype.setArray2 = function (uniform, array) {
  13452. if (!uniform || array.length % 2 !== 0)
  13453. return;
  13454. this._gl.uniform2fv(uniform, array);
  13455. };
  13456. /**
  13457. * Set the value of an uniform to an array of number (stored as vec3)
  13458. * @param uniform defines the webGL uniform location where to store the value
  13459. * @param array defines the array of number to store
  13460. */
  13461. Engine.prototype.setArray3 = function (uniform, array) {
  13462. if (!uniform || array.length % 3 !== 0)
  13463. return;
  13464. this._gl.uniform3fv(uniform, array);
  13465. };
  13466. /**
  13467. * Set the value of an uniform to an array of number (stored as vec4)
  13468. * @param uniform defines the webGL uniform location where to store the value
  13469. * @param array defines the array of number to store
  13470. */
  13471. Engine.prototype.setArray4 = function (uniform, array) {
  13472. if (!uniform || array.length % 4 !== 0)
  13473. return;
  13474. this._gl.uniform4fv(uniform, array);
  13475. };
  13476. /**
  13477. * Set the value of an uniform to an array of float32 (stored as matrices)
  13478. * @param uniform defines the webGL uniform location where to store the value
  13479. * @param matrices defines the array of float32 to store
  13480. */
  13481. Engine.prototype.setMatrices = function (uniform, matrices) {
  13482. if (!uniform)
  13483. return;
  13484. this._gl.uniformMatrix4fv(uniform, false, matrices);
  13485. };
  13486. /**
  13487. * Set the value of an uniform to a matrix
  13488. * @param uniform defines the webGL uniform location where to store the value
  13489. * @param matrix defines the matrix to store
  13490. */
  13491. Engine.prototype.setMatrix = function (uniform, matrix) {
  13492. if (!uniform)
  13493. return;
  13494. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  13495. };
  13496. /**
  13497. * Set the value of an uniform to a matrix (3x3)
  13498. * @param uniform defines the webGL uniform location where to store the value
  13499. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  13500. */
  13501. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  13502. if (!uniform)
  13503. return;
  13504. this._gl.uniformMatrix3fv(uniform, false, matrix);
  13505. };
  13506. /**
  13507. * Set the value of an uniform to a matrix (2x2)
  13508. * @param uniform defines the webGL uniform location where to store the value
  13509. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  13510. */
  13511. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  13512. if (!uniform)
  13513. return;
  13514. this._gl.uniformMatrix2fv(uniform, false, matrix);
  13515. };
  13516. /**
  13517. * Set the value of an uniform to a number (int)
  13518. * @param uniform defines the webGL uniform location where to store the value
  13519. * @param value defines the int number to store
  13520. */
  13521. Engine.prototype.setInt = function (uniform, value) {
  13522. if (!uniform)
  13523. return;
  13524. this._gl.uniform1i(uniform, value);
  13525. };
  13526. /**
  13527. * Set the value of an uniform to a number (float)
  13528. * @param uniform defines the webGL uniform location where to store the value
  13529. * @param value defines the float number to store
  13530. */
  13531. Engine.prototype.setFloat = function (uniform, value) {
  13532. if (!uniform)
  13533. return;
  13534. this._gl.uniform1f(uniform, value);
  13535. };
  13536. /**
  13537. * Set the value of an uniform to a vec2
  13538. * @param uniform defines the webGL uniform location where to store the value
  13539. * @param x defines the 1st component of the value
  13540. * @param y defines the 2nd component of the value
  13541. */
  13542. Engine.prototype.setFloat2 = function (uniform, x, y) {
  13543. if (!uniform)
  13544. return;
  13545. this._gl.uniform2f(uniform, x, y);
  13546. };
  13547. /**
  13548. * Set the value of an uniform to a vec3
  13549. * @param uniform defines the webGL uniform location where to store the value
  13550. * @param x defines the 1st component of the value
  13551. * @param y defines the 2nd component of the value
  13552. * @param z defines the 3rd component of the value
  13553. */
  13554. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  13555. if (!uniform)
  13556. return;
  13557. this._gl.uniform3f(uniform, x, y, z);
  13558. };
  13559. /**
  13560. * Set the value of an uniform to a boolean
  13561. * @param uniform defines the webGL uniform location where to store the value
  13562. * @param bool defines the boolean to store
  13563. */
  13564. Engine.prototype.setBool = function (uniform, bool) {
  13565. if (!uniform)
  13566. return;
  13567. this._gl.uniform1i(uniform, bool);
  13568. };
  13569. /**
  13570. * Set the value of an uniform to a vec4
  13571. * @param uniform defines the webGL uniform location where to store the value
  13572. * @param x defines the 1st component of the value
  13573. * @param y defines the 2nd component of the value
  13574. * @param z defines the 3rd component of the value
  13575. * @param w defines the 4th component of the value
  13576. */
  13577. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  13578. if (!uniform)
  13579. return;
  13580. this._gl.uniform4f(uniform, x, y, z, w);
  13581. };
  13582. /**
  13583. * Set the value of an uniform to a Color3
  13584. * @param uniform defines the webGL uniform location where to store the value
  13585. * @param color3 defines the color to store
  13586. */
  13587. Engine.prototype.setColor3 = function (uniform, color3) {
  13588. if (!uniform)
  13589. return;
  13590. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  13591. };
  13592. /**
  13593. * Set the value of an uniform to a Color3 and an alpha value
  13594. * @param uniform defines the webGL uniform location where to store the value
  13595. * @param color3 defines the color to store
  13596. * @param alpha defines the alpha component to store
  13597. */
  13598. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  13599. if (!uniform)
  13600. return;
  13601. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  13602. };
  13603. /**
  13604. * Sets a Color4 on a uniform variable
  13605. * @param uniform defines the uniform location
  13606. * @param color4 defines the value to be set
  13607. */
  13608. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  13609. if (!uniform)
  13610. return;
  13611. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  13612. };
  13613. // States
  13614. /**
  13615. * Set various states to the webGL context
  13616. * @param culling defines backface culling state
  13617. * @param zOffset defines the value to apply to zOffset (0 by default)
  13618. * @param force defines if states must be applied even if cache is up to date
  13619. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  13620. */
  13621. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  13622. if (zOffset === void 0) { zOffset = 0; }
  13623. if (reverseSide === void 0) { reverseSide = false; }
  13624. // Culling
  13625. if (this._depthCullingState.cull !== culling || force) {
  13626. this._depthCullingState.cull = culling;
  13627. }
  13628. // Cull face
  13629. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  13630. if (this._depthCullingState.cullFace !== cullFace || force) {
  13631. this._depthCullingState.cullFace = cullFace;
  13632. }
  13633. // Z offset
  13634. this.setZOffset(zOffset);
  13635. // Front face
  13636. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  13637. if (this._depthCullingState.frontFace !== frontFace || force) {
  13638. this._depthCullingState.frontFace = frontFace;
  13639. }
  13640. };
  13641. /**
  13642. * Set the z offset to apply to current rendering
  13643. * @param value defines the offset to apply
  13644. */
  13645. Engine.prototype.setZOffset = function (value) {
  13646. this._depthCullingState.zOffset = value;
  13647. };
  13648. /**
  13649. * Gets the current value of the zOffset
  13650. * @returns the current zOffset state
  13651. */
  13652. Engine.prototype.getZOffset = function () {
  13653. return this._depthCullingState.zOffset;
  13654. };
  13655. /**
  13656. * Enable or disable depth buffering
  13657. * @param enable defines the state to set
  13658. */
  13659. Engine.prototype.setDepthBuffer = function (enable) {
  13660. this._depthCullingState.depthTest = enable;
  13661. };
  13662. /**
  13663. * Gets a boolean indicating if depth writing is enabled
  13664. * @returns the current depth writing state
  13665. */
  13666. Engine.prototype.getDepthWrite = function () {
  13667. return this._depthCullingState.depthMask;
  13668. };
  13669. /**
  13670. * Enable or disable depth writing
  13671. * @param enable defines the state to set
  13672. */
  13673. Engine.prototype.setDepthWrite = function (enable) {
  13674. this._depthCullingState.depthMask = enable;
  13675. };
  13676. /**
  13677. * Enable or disable color writing
  13678. * @param enable defines the state to set
  13679. */
  13680. Engine.prototype.setColorWrite = function (enable) {
  13681. this._gl.colorMask(enable, enable, enable, enable);
  13682. this._colorWrite = enable;
  13683. };
  13684. /**
  13685. * Gets a boolean indicating if color writing is enabled
  13686. * @returns the current color writing state
  13687. */
  13688. Engine.prototype.getColorWrite = function () {
  13689. return this._colorWrite;
  13690. };
  13691. /**
  13692. * Sets alpha constants used by some alpha blending modes
  13693. * @param r defines the red component
  13694. * @param g defines the green component
  13695. * @param b defines the blue component
  13696. * @param a defines the alpha component
  13697. */
  13698. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  13699. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  13700. };
  13701. /**
  13702. * Sets the current alpha mode
  13703. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  13704. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  13705. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  13706. */
  13707. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  13708. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  13709. if (this._alphaMode === mode) {
  13710. return;
  13711. }
  13712. switch (mode) {
  13713. case Engine.ALPHA_DISABLE:
  13714. this._alphaState.alphaBlend = false;
  13715. break;
  13716. case Engine.ALPHA_PREMULTIPLIED:
  13717. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  13718. this._alphaState.alphaBlend = true;
  13719. break;
  13720. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  13721. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  13722. this._alphaState.alphaBlend = true;
  13723. break;
  13724. case Engine.ALPHA_COMBINE:
  13725. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  13726. this._alphaState.alphaBlend = true;
  13727. break;
  13728. case Engine.ALPHA_ONEONE:
  13729. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  13730. this._alphaState.alphaBlend = true;
  13731. break;
  13732. case Engine.ALPHA_ADD:
  13733. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  13734. this._alphaState.alphaBlend = true;
  13735. break;
  13736. case Engine.ALPHA_SUBTRACT:
  13737. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  13738. this._alphaState.alphaBlend = true;
  13739. break;
  13740. case Engine.ALPHA_MULTIPLY:
  13741. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  13742. this._alphaState.alphaBlend = true;
  13743. break;
  13744. case Engine.ALPHA_MAXIMIZED:
  13745. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  13746. this._alphaState.alphaBlend = true;
  13747. break;
  13748. case Engine.ALPHA_INTERPOLATE:
  13749. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  13750. this._alphaState.alphaBlend = true;
  13751. break;
  13752. case Engine.ALPHA_SCREENMODE:
  13753. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  13754. this._alphaState.alphaBlend = true;
  13755. break;
  13756. }
  13757. if (!noDepthWriteChange) {
  13758. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  13759. }
  13760. this._alphaMode = mode;
  13761. };
  13762. /**
  13763. * Gets the current alpha mode
  13764. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  13765. * @returns the current alpha mode
  13766. */
  13767. Engine.prototype.getAlphaMode = function () {
  13768. return this._alphaMode;
  13769. };
  13770. // Textures
  13771. /**
  13772. * Force the entire cache to be cleared
  13773. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  13774. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  13775. */
  13776. Engine.prototype.wipeCaches = function (bruteForce) {
  13777. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  13778. return;
  13779. }
  13780. this._currentEffect = null;
  13781. if (bruteForce) {
  13782. this.resetTextureCache();
  13783. this._currentProgram = null;
  13784. this._stencilState.reset();
  13785. this._depthCullingState.reset();
  13786. this.setDepthFunctionToLessOrEqual();
  13787. this._alphaState.reset();
  13788. }
  13789. this._resetVertexBufferBinding();
  13790. this._cachedIndexBuffer = null;
  13791. this._cachedEffectForVertexBuffers = null;
  13792. this._unbindVertexArrayObject();
  13793. this.bindIndexBuffer(null);
  13794. };
  13795. /**
  13796. * Set the compressed texture format to use, based on the formats you have, and the formats
  13797. * supported by the hardware / browser.
  13798. *
  13799. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  13800. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  13801. * to API arguments needed to compressed textures. This puts the burden on the container
  13802. * generator to house the arcane code for determining these for current & future formats.
  13803. *
  13804. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  13805. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  13806. *
  13807. * Note: The result of this call is not taken into account when a texture is base64.
  13808. *
  13809. * @param formatsAvailable defines the list of those format families you have created
  13810. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  13811. *
  13812. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  13813. * @returns The extension selected.
  13814. */
  13815. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  13816. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  13817. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  13818. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  13819. return this._textureFormatInUse = this._texturesSupported[i];
  13820. }
  13821. }
  13822. }
  13823. // actively set format to nothing, to allow this to be called more than once
  13824. // and possibly fail the 2nd time
  13825. this._textureFormatInUse = null;
  13826. return null;
  13827. };
  13828. /** @ignore */
  13829. Engine.prototype._createTexture = function () {
  13830. var texture = this._gl.createTexture();
  13831. if (!texture) {
  13832. throw new Error("Unable to create texture");
  13833. }
  13834. return texture;
  13835. };
  13836. /**
  13837. * Usually called from BABYLON.Texture.ts.
  13838. * Passed information to create a WebGLTexture
  13839. * @param urlArg defines a value which contains one of the following:
  13840. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  13841. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  13842. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  13843. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  13844. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  13845. * @param scene needed for loading to the correct scene
  13846. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  13847. * @param onLoad optional callback to be called upon successful completion
  13848. * @param onError optional callback to be called upon failure
  13849. * @param buffer a source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  13850. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  13851. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  13852. * @returns a InternalTexture for assignment back into BABYLON.Texture
  13853. */
  13854. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  13855. var _this = this;
  13856. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13857. if (onLoad === void 0) { onLoad = null; }
  13858. if (onError === void 0) { onError = null; }
  13859. if (buffer === void 0) { buffer = null; }
  13860. if (fallback === void 0) { fallback = null; }
  13861. if (format === void 0) { format = null; }
  13862. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  13863. var fromData = url.substr(0, 5) === "data:";
  13864. var fromBlob = url.substr(0, 5) === "blob:";
  13865. var isBase64 = fromData && url.indexOf("base64") !== -1;
  13866. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  13867. // establish the file extension, if possible
  13868. var lastDot = url.lastIndexOf('.');
  13869. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  13870. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  13871. var isTGA = (extension.indexOf(".tga") === 0);
  13872. // determine if a ktx file should be substituted
  13873. var isKTX = false;
  13874. if (this._textureFormatInUse && !isBase64 && !fallback) {
  13875. url = url.substring(0, lastDot) + this._textureFormatInUse;
  13876. isKTX = true;
  13877. }
  13878. if (scene) {
  13879. scene._addPendingData(texture);
  13880. }
  13881. texture.url = url;
  13882. texture.generateMipMaps = !noMipmap;
  13883. texture.samplingMode = samplingMode;
  13884. texture.invertY = invertY;
  13885. if (!this._doNotHandleContextLost) {
  13886. // Keep a link to the buffer only if we plan to handle context lost
  13887. texture._buffer = buffer;
  13888. }
  13889. var onLoadObserver = null;
  13890. if (onLoad && !fallback) {
  13891. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  13892. }
  13893. if (!fallback)
  13894. this._internalTexturesCache.push(texture);
  13895. var onerror = function (message, exception) {
  13896. if (scene) {
  13897. scene._removePendingData(texture);
  13898. }
  13899. if (onLoadObserver) {
  13900. texture.onLoadedObservable.remove(onLoadObserver);
  13901. }
  13902. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  13903. if (isKTX) {
  13904. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13905. }
  13906. else if (BABYLON.Tools.UseFallbackTexture) {
  13907. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13908. }
  13909. if (onError) {
  13910. onError(message || "Unknown error", exception);
  13911. }
  13912. };
  13913. var callback = null;
  13914. // processing for non-image formats
  13915. if (isKTX || isTGA || isDDS) {
  13916. if (isKTX) {
  13917. callback = function (data) {
  13918. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  13919. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  13920. ktx.uploadLevels(_this._gl, !noMipmap);
  13921. return false;
  13922. }, samplingMode);
  13923. };
  13924. }
  13925. else if (isTGA) {
  13926. callback = function (arrayBuffer) {
  13927. var data = new Uint8Array(arrayBuffer);
  13928. var header = BABYLON.TGATools.GetTGAHeader(data);
  13929. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  13930. BABYLON.TGATools.UploadContent(_this._gl, data);
  13931. return false;
  13932. }, samplingMode);
  13933. };
  13934. }
  13935. else if (isDDS) {
  13936. callback = function (data) {
  13937. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13938. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  13939. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  13940. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  13941. return false;
  13942. }, samplingMode);
  13943. };
  13944. }
  13945. if (!buffer) {
  13946. this._loadFile(url, function (data) {
  13947. if (callback) {
  13948. callback(data);
  13949. }
  13950. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  13951. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  13952. });
  13953. }
  13954. else {
  13955. if (callback) {
  13956. callback(buffer);
  13957. }
  13958. }
  13959. // image format processing
  13960. }
  13961. else {
  13962. var onload = function (img) {
  13963. if (fromBlob && !_this._doNotHandleContextLost) {
  13964. // We need to store the image if we need to rebuild the texture
  13965. // in case of a webgl context lost
  13966. texture._buffer = img;
  13967. }
  13968. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  13969. var gl = _this._gl;
  13970. var isPot = (img.width === potWidth && img.height === potHeight);
  13971. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  13972. if (isPot) {
  13973. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13974. return false;
  13975. }
  13976. // Using shaders to rescale because canvas.drawImage is lossy
  13977. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13978. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  13979. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13980. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13981. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13982. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13983. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13984. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  13985. _this._releaseTexture(source);
  13986. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13987. continuationCallback();
  13988. });
  13989. return true;
  13990. }, samplingMode);
  13991. };
  13992. if (!fromData || isBase64)
  13993. if (buffer instanceof HTMLImageElement) {
  13994. onload(buffer);
  13995. }
  13996. else {
  13997. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  13998. }
  13999. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  14000. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14001. else
  14002. onload(buffer);
  14003. }
  14004. return texture;
  14005. };
  14006. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14007. var _this = this;
  14008. var rtt = this.createRenderTargetTexture({
  14009. width: destination.width,
  14010. height: destination.height,
  14011. }, {
  14012. generateMipMaps: false,
  14013. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14014. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14015. generateDepthBuffer: false,
  14016. generateStencilBuffer: false
  14017. });
  14018. if (!this._rescalePostProcess) {
  14019. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14020. }
  14021. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14022. _this._rescalePostProcess.onApply = function (effect) {
  14023. effect._bindTexture("textureSampler", source);
  14024. };
  14025. var hostingScene = scene;
  14026. if (!hostingScene) {
  14027. hostingScene = _this.scenes[_this.scenes.length - 1];
  14028. }
  14029. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14030. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14031. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14032. _this.unBindFramebuffer(rtt);
  14033. _this._releaseTexture(rtt);
  14034. if (onComplete) {
  14035. onComplete();
  14036. }
  14037. });
  14038. };
  14039. /**
  14040. * Update a raw texture
  14041. * @param texture defines the texture to update
  14042. * @param data defines the data to store in the texture
  14043. * @param format defines the format of the data
  14044. * @param invertY defines if data must be stored with Y axis inverted
  14045. * @param compression defines the compression used (null by default)
  14046. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14047. */
  14048. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14049. if (compression === void 0) { compression = null; }
  14050. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14051. if (!texture) {
  14052. return;
  14053. }
  14054. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14055. var internalFormat = this._getInternalFormat(format);
  14056. var textureType = this._getWebGLTextureType(type);
  14057. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14058. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14059. if (!this._doNotHandleContextLost) {
  14060. texture._bufferView = data;
  14061. texture.format = format;
  14062. texture.type = type;
  14063. texture.invertY = invertY;
  14064. texture._compression = compression;
  14065. }
  14066. if (texture.width % 4 !== 0) {
  14067. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14068. }
  14069. if (compression && data) {
  14070. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14071. }
  14072. else {
  14073. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14074. }
  14075. if (texture.generateMipMaps) {
  14076. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14077. }
  14078. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14079. // this.resetTextureCache();
  14080. texture.isReady = true;
  14081. };
  14082. /**
  14083. * Creates a raw texture
  14084. * @param data defines the data to store in the texture
  14085. * @param width defines the width of the texture
  14086. * @param height defines the height of the texture
  14087. * @param format defines the format of the data
  14088. * @param generateMipMaps defines if the engine should generate the mip levels
  14089. * @param invertY defines if data must be stored with Y axis inverted
  14090. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14091. * @param compression defines the compression used (null by default)
  14092. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14093. * @returns the raw texture inside an InternalTexture
  14094. */
  14095. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14096. if (compression === void 0) { compression = null; }
  14097. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14098. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14099. texture.baseWidth = width;
  14100. texture.baseHeight = height;
  14101. texture.width = width;
  14102. texture.height = height;
  14103. texture.format = format;
  14104. texture.generateMipMaps = generateMipMaps;
  14105. texture.samplingMode = samplingMode;
  14106. texture.invertY = invertY;
  14107. texture._compression = compression;
  14108. texture.type = type;
  14109. if (!this._doNotHandleContextLost) {
  14110. texture._bufferView = data;
  14111. }
  14112. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14113. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14114. // Filters
  14115. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14116. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14117. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14118. if (generateMipMaps) {
  14119. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14120. }
  14121. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14122. this._internalTexturesCache.push(texture);
  14123. return texture;
  14124. };
  14125. /**
  14126. * Creates a dynamic texture
  14127. * @param width defines the width of the texture
  14128. * @param height defines the height of the texture
  14129. * @param generateMipMaps defines if the engine should generate the mip levels
  14130. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14131. * @returns the dynamic texture inside an InternalTexture
  14132. */
  14133. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14134. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14135. texture.baseWidth = width;
  14136. texture.baseHeight = height;
  14137. if (generateMipMaps) {
  14138. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14139. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14140. }
  14141. // this.resetTextureCache();
  14142. texture.width = width;
  14143. texture.height = height;
  14144. texture.isReady = false;
  14145. texture.generateMipMaps = generateMipMaps;
  14146. texture.samplingMode = samplingMode;
  14147. this.updateTextureSamplingMode(samplingMode, texture);
  14148. this._internalTexturesCache.push(texture);
  14149. return texture;
  14150. };
  14151. /**
  14152. * Update the sampling mode of a given texture
  14153. * @param samplingMode defines the required sampling mode
  14154. * @param texture defines the texture to update
  14155. */
  14156. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14157. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14158. if (texture.isCube) {
  14159. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14160. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14161. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14162. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14163. }
  14164. else if (texture.is3D) {
  14165. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14166. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14167. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14168. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14169. }
  14170. else {
  14171. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14172. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14173. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14174. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14175. }
  14176. texture.samplingMode = samplingMode;
  14177. };
  14178. /**
  14179. * Update the content of a dynamic texture
  14180. * @param texture defines the texture to update
  14181. * @param canvas defines the canvas containing the source
  14182. * @param invertY defines if data must be stored with Y axis inverted
  14183. * @param premulAlpha defines if alpha is stored as premultiplied
  14184. * @param format defines the format of the data
  14185. */
  14186. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14187. if (premulAlpha === void 0) { premulAlpha = false; }
  14188. if (!texture) {
  14189. return;
  14190. }
  14191. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14192. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  14193. if (premulAlpha) {
  14194. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14195. }
  14196. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14197. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14198. if (texture.generateMipMaps) {
  14199. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14200. }
  14201. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14202. if (premulAlpha) {
  14203. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14204. }
  14205. texture.isReady = true;
  14206. };
  14207. /**
  14208. * Update a video texture
  14209. * @param texture defines the texture to update
  14210. * @param video defines the video element to use
  14211. * @param invertY defines if data must be stored with Y axis inverted
  14212. */
  14213. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14214. if (!texture || texture._isDisabled) {
  14215. return;
  14216. }
  14217. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14218. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  14219. try {
  14220. // Testing video texture support
  14221. if (this._videoTextureSupported === undefined) {
  14222. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14223. if (this._gl.getError() !== 0) {
  14224. this._videoTextureSupported = false;
  14225. }
  14226. else {
  14227. this._videoTextureSupported = true;
  14228. }
  14229. }
  14230. // Copy video through the current working canvas if video texture is not supported
  14231. if (!this._videoTextureSupported) {
  14232. if (!texture._workingCanvas) {
  14233. texture._workingCanvas = document.createElement("canvas");
  14234. var context = texture._workingCanvas.getContext("2d");
  14235. if (!context) {
  14236. throw new Error("Unable to get 2d context");
  14237. }
  14238. texture._workingContext = context;
  14239. texture._workingCanvas.width = texture.width;
  14240. texture._workingCanvas.height = texture.height;
  14241. }
  14242. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14243. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14244. }
  14245. else {
  14246. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14247. }
  14248. if (texture.generateMipMaps) {
  14249. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14250. }
  14251. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14252. // this.resetTextureCache();
  14253. texture.isReady = true;
  14254. }
  14255. catch (ex) {
  14256. // Something unexpected
  14257. // Let's disable the texture
  14258. texture._isDisabled = true;
  14259. }
  14260. };
  14261. /**
  14262. * Updates a depth texture Comparison Mode and Function.
  14263. * If the comparison Function is equal to 0, the mode will be set to none.
  14264. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14265. * @param texture The texture to set the comparison function for
  14266. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14267. */
  14268. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14269. if (this.webGLVersion === 1) {
  14270. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14271. return;
  14272. }
  14273. var gl = this._gl;
  14274. if (texture.isCube) {
  14275. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14276. if (comparisonFunction === 0) {
  14277. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14278. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14279. }
  14280. else {
  14281. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14282. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14283. }
  14284. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14285. }
  14286. else {
  14287. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14288. if (comparisonFunction === 0) {
  14289. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14290. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14291. }
  14292. else {
  14293. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14294. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14295. }
  14296. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14297. }
  14298. texture._comparisonFunction = comparisonFunction;
  14299. };
  14300. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14301. var width = size.width || size;
  14302. var height = size.height || size;
  14303. internalTexture.baseWidth = width;
  14304. internalTexture.baseHeight = height;
  14305. internalTexture.width = width;
  14306. internalTexture.height = height;
  14307. internalTexture.isReady = true;
  14308. internalTexture.samples = 1;
  14309. internalTexture.generateMipMaps = false;
  14310. internalTexture._generateDepthBuffer = true;
  14311. internalTexture._generateStencilBuffer = generateStencil;
  14312. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14313. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14314. internalTexture._comparisonFunction = comparisonFunction;
  14315. var gl = this._gl;
  14316. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14317. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  14318. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14319. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14320. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14321. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14322. if (comparisonFunction === 0) {
  14323. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14324. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14325. }
  14326. else {
  14327. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14328. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14329. }
  14330. };
  14331. /**
  14332. * Creates a depth stencil texture.
  14333. * This is only available in WebGL 2 or with the depth texture extension available.
  14334. * @param size The size of face edge in the texture.
  14335. * @param options The options defining the texture.
  14336. * @returns The texture
  14337. */
  14338. Engine.prototype.createDepthStencilTexture = function (size, options) {
  14339. if (options.isCube) {
  14340. var width = size.width || size;
  14341. return this._createDepthStencilCubeTexture(width, options);
  14342. }
  14343. else {
  14344. return this._createDepthStencilTexture(size, options);
  14345. }
  14346. };
  14347. /**
  14348. * Creates a depth stencil texture.
  14349. * This is only available in WebGL 2 or with the depth texture extension available.
  14350. * @param size The size of face edge in the texture.
  14351. * @param options The options defining the texture.
  14352. * @returns The texture
  14353. */
  14354. Engine.prototype._createDepthStencilTexture = function (size, options) {
  14355. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  14356. if (!this._caps.depthTextureExtension) {
  14357. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  14358. return internalTexture;
  14359. }
  14360. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14361. var gl = this._gl;
  14362. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  14363. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14364. if (this.webGLVersion > 1) {
  14365. if (internalOptions.generateStencil) {
  14366. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14367. }
  14368. else {
  14369. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14370. }
  14371. }
  14372. else {
  14373. if (internalOptions.generateStencil) {
  14374. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14375. }
  14376. else {
  14377. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14378. }
  14379. }
  14380. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14381. return internalTexture;
  14382. };
  14383. /**
  14384. * Creates a depth stencil cube texture.
  14385. * This is only available in WebGL 2.
  14386. * @param size The size of face edge in the cube texture.
  14387. * @param options The options defining the cube texture.
  14388. * @returns The cube texture
  14389. */
  14390. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  14391. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  14392. internalTexture.isCube = true;
  14393. if (this.webGLVersion === 1) {
  14394. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  14395. return internalTexture;
  14396. }
  14397. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14398. var gl = this._gl;
  14399. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  14400. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14401. // Create the depth/stencil buffer
  14402. for (var face = 0; face < 6; face++) {
  14403. if (internalOptions.generateStencil) {
  14404. 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);
  14405. }
  14406. else {
  14407. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14408. }
  14409. }
  14410. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14411. return internalTexture;
  14412. };
  14413. /**
  14414. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  14415. * @param renderTarget The render target to set the frame buffer for
  14416. */
  14417. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  14418. // Create the framebuffer
  14419. var internalTexture = renderTarget.getInternalTexture();
  14420. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  14421. return;
  14422. }
  14423. var gl = this._gl;
  14424. var depthStencilTexture = renderTarget.depthStencilTexture;
  14425. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  14426. if (depthStencilTexture.isCube) {
  14427. if (depthStencilTexture._generateStencilBuffer) {
  14428. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  14429. }
  14430. else {
  14431. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  14432. }
  14433. }
  14434. else {
  14435. if (depthStencilTexture._generateStencilBuffer) {
  14436. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  14437. }
  14438. else {
  14439. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  14440. }
  14441. }
  14442. this.bindUnboundFramebuffer(null);
  14443. };
  14444. /**
  14445. * Creates a new render target texture
  14446. * @param size defines the size of the texture
  14447. * @param options defines the options used to create the texture
  14448. * @returns a new render target texture stored in an InternalTexture
  14449. */
  14450. Engine.prototype.createRenderTargetTexture = function (size, options) {
  14451. var fullOptions = new RenderTargetCreationOptions();
  14452. if (options !== undefined && typeof options === "object") {
  14453. fullOptions.generateMipMaps = options.generateMipMaps;
  14454. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  14455. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  14456. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  14457. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  14458. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  14459. }
  14460. else {
  14461. fullOptions.generateMipMaps = options;
  14462. fullOptions.generateDepthBuffer = true;
  14463. fullOptions.generateStencilBuffer = false;
  14464. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14465. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  14466. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  14467. }
  14468. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  14469. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  14470. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14471. }
  14472. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  14473. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  14474. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14475. }
  14476. var gl = this._gl;
  14477. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  14478. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14479. var width = size.width || size;
  14480. var height = size.height || size;
  14481. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  14482. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  14483. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14484. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  14485. }
  14486. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14487. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14488. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14489. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14490. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  14491. // Create the framebuffer
  14492. var framebuffer = gl.createFramebuffer();
  14493. this.bindUnboundFramebuffer(framebuffer);
  14494. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  14495. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  14496. if (fullOptions.generateMipMaps) {
  14497. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14498. }
  14499. // Unbind
  14500. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14501. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  14502. this.bindUnboundFramebuffer(null);
  14503. texture._framebuffer = framebuffer;
  14504. texture.baseWidth = width;
  14505. texture.baseHeight = height;
  14506. texture.width = width;
  14507. texture.height = height;
  14508. texture.isReady = true;
  14509. texture.samples = 1;
  14510. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  14511. texture.samplingMode = fullOptions.samplingMode;
  14512. texture.type = fullOptions.type;
  14513. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  14514. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  14515. // this.resetTextureCache();
  14516. this._internalTexturesCache.push(texture);
  14517. return texture;
  14518. };
  14519. /**
  14520. * Create a multi render target texture
  14521. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  14522. * @param size defines the size of the texture
  14523. * @param options defines the creation options
  14524. * @returns the cube texture as an InternalTexture
  14525. */
  14526. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  14527. var generateMipMaps = false;
  14528. var generateDepthBuffer = true;
  14529. var generateStencilBuffer = false;
  14530. var generateDepthTexture = false;
  14531. var textureCount = 1;
  14532. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  14533. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  14534. var types = new Array();
  14535. var samplingModes = new Array();
  14536. if (options !== undefined) {
  14537. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  14538. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  14539. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  14540. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  14541. textureCount = options.textureCount || 1;
  14542. if (options.types) {
  14543. types = options.types;
  14544. }
  14545. if (options.samplingModes) {
  14546. samplingModes = options.samplingModes;
  14547. }
  14548. }
  14549. var gl = this._gl;
  14550. // Create the framebuffer
  14551. var framebuffer = gl.createFramebuffer();
  14552. this.bindUnboundFramebuffer(framebuffer);
  14553. var width = size.width || size;
  14554. var height = size.height || size;
  14555. var textures = [];
  14556. var attachments = [];
  14557. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  14558. for (var i = 0; i < textureCount; i++) {
  14559. var samplingMode = samplingModes[i] || defaultSamplingMode;
  14560. var type = types[i] || defaultType;
  14561. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  14562. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  14563. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14564. }
  14565. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  14566. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  14567. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14568. }
  14569. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  14570. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  14571. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14572. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  14573. }
  14574. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  14575. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  14576. textures.push(texture);
  14577. attachments.push(attachment);
  14578. gl.activeTexture(gl["TEXTURE" + i]);
  14579. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  14580. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14581. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14582. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14583. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14584. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  14585. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  14586. if (generateMipMaps) {
  14587. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14588. }
  14589. // Unbind
  14590. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14591. texture._framebuffer = framebuffer;
  14592. texture._depthStencilBuffer = depthStencilBuffer;
  14593. texture.baseWidth = width;
  14594. texture.baseHeight = height;
  14595. texture.width = width;
  14596. texture.height = height;
  14597. texture.isReady = true;
  14598. texture.samples = 1;
  14599. texture.generateMipMaps = generateMipMaps;
  14600. texture.samplingMode = samplingMode;
  14601. texture.type = type;
  14602. texture._generateDepthBuffer = generateDepthBuffer;
  14603. texture._generateStencilBuffer = generateStencilBuffer;
  14604. texture._attachments = attachments;
  14605. this._internalTexturesCache.push(texture);
  14606. }
  14607. if (generateDepthTexture && this._caps.depthTextureExtension) {
  14608. // Depth texture
  14609. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  14610. gl.activeTexture(gl.TEXTURE0);
  14611. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  14612. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14613. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14614. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14615. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14616. 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);
  14617. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  14618. depthTexture._framebuffer = framebuffer;
  14619. depthTexture.baseWidth = width;
  14620. depthTexture.baseHeight = height;
  14621. depthTexture.width = width;
  14622. depthTexture.height = height;
  14623. depthTexture.isReady = true;
  14624. depthTexture.samples = 1;
  14625. depthTexture.generateMipMaps = generateMipMaps;
  14626. depthTexture.samplingMode = gl.NEAREST;
  14627. depthTexture._generateDepthBuffer = generateDepthBuffer;
  14628. depthTexture._generateStencilBuffer = generateStencilBuffer;
  14629. textures.push(depthTexture);
  14630. this._internalTexturesCache.push(depthTexture);
  14631. }
  14632. gl.drawBuffers(attachments);
  14633. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  14634. this.bindUnboundFramebuffer(null);
  14635. this.resetTextureCache();
  14636. return textures;
  14637. };
  14638. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  14639. if (samples === void 0) { samples = 1; }
  14640. var depthStencilBuffer = null;
  14641. var gl = this._gl;
  14642. // Create the depth/stencil buffer
  14643. if (generateStencilBuffer) {
  14644. depthStencilBuffer = gl.createRenderbuffer();
  14645. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  14646. if (samples > 1) {
  14647. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  14648. }
  14649. else {
  14650. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  14651. }
  14652. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  14653. }
  14654. else if (generateDepthBuffer) {
  14655. depthStencilBuffer = gl.createRenderbuffer();
  14656. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  14657. if (samples > 1) {
  14658. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  14659. }
  14660. else {
  14661. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  14662. }
  14663. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  14664. }
  14665. return depthStencilBuffer;
  14666. };
  14667. /**
  14668. * Updates the sample count of a render target texture
  14669. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  14670. * @param texture defines the texture to update
  14671. * @param samples defines the sample count to set
  14672. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  14673. */
  14674. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  14675. if (this.webGLVersion < 2 || !texture) {
  14676. return 1;
  14677. }
  14678. if (texture.samples === samples) {
  14679. return samples;
  14680. }
  14681. var gl = this._gl;
  14682. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  14683. // Dispose previous render buffers
  14684. if (texture._depthStencilBuffer) {
  14685. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14686. texture._depthStencilBuffer = null;
  14687. }
  14688. if (texture._MSAAFramebuffer) {
  14689. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14690. texture._MSAAFramebuffer = null;
  14691. }
  14692. if (texture._MSAARenderBuffer) {
  14693. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14694. texture._MSAARenderBuffer = null;
  14695. }
  14696. if (samples > 1) {
  14697. var framebuffer = gl.createFramebuffer();
  14698. if (!framebuffer) {
  14699. throw new Error("Unable to create multi sampled framebuffer");
  14700. }
  14701. texture._MSAAFramebuffer = framebuffer;
  14702. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  14703. var colorRenderbuffer = gl.createRenderbuffer();
  14704. if (!colorRenderbuffer) {
  14705. throw new Error("Unable to create multi sampled framebuffer");
  14706. }
  14707. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  14708. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  14709. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  14710. texture._MSAARenderBuffer = colorRenderbuffer;
  14711. }
  14712. else {
  14713. this.bindUnboundFramebuffer(texture._framebuffer);
  14714. }
  14715. texture.samples = samples;
  14716. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  14717. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  14718. this.bindUnboundFramebuffer(null);
  14719. return samples;
  14720. };
  14721. /**
  14722. * Update the sample count for a given multiple render target texture
  14723. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  14724. * @param textures defines the textures to update
  14725. * @param samples defines the sample count to set
  14726. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  14727. */
  14728. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  14729. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  14730. return 1;
  14731. }
  14732. if (textures[0].samples === samples) {
  14733. return samples;
  14734. }
  14735. var gl = this._gl;
  14736. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  14737. // Dispose previous render buffers
  14738. if (textures[0]._depthStencilBuffer) {
  14739. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  14740. textures[0]._depthStencilBuffer = null;
  14741. }
  14742. if (textures[0]._MSAAFramebuffer) {
  14743. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  14744. textures[0]._MSAAFramebuffer = null;
  14745. }
  14746. for (var i = 0; i < textures.length; i++) {
  14747. if (textures[i]._MSAARenderBuffer) {
  14748. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  14749. textures[i]._MSAARenderBuffer = null;
  14750. }
  14751. }
  14752. if (samples > 1) {
  14753. var framebuffer = gl.createFramebuffer();
  14754. if (!framebuffer) {
  14755. throw new Error("Unable to create multi sampled framebuffer");
  14756. }
  14757. this.bindUnboundFramebuffer(framebuffer);
  14758. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  14759. var attachments = [];
  14760. for (var i = 0; i < textures.length; i++) {
  14761. var texture = textures[i];
  14762. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  14763. var colorRenderbuffer = gl.createRenderbuffer();
  14764. if (!colorRenderbuffer) {
  14765. throw new Error("Unable to create multi sampled framebuffer");
  14766. }
  14767. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  14768. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  14769. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  14770. texture._MSAAFramebuffer = framebuffer;
  14771. texture._MSAARenderBuffer = colorRenderbuffer;
  14772. texture.samples = samples;
  14773. texture._depthStencilBuffer = depthStencilBuffer;
  14774. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  14775. attachments.push(attachment);
  14776. }
  14777. gl.drawBuffers(attachments);
  14778. }
  14779. else {
  14780. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  14781. }
  14782. this.bindUnboundFramebuffer(null);
  14783. return samples;
  14784. };
  14785. /** @ignore */
  14786. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  14787. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  14788. };
  14789. /** @ignore */
  14790. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  14791. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  14792. };
  14793. /**
  14794. * Creates a new render target cube texture
  14795. * @param size defines the size of the texture
  14796. * @param options defines the options used to create the texture
  14797. * @returns a new render target cube texture stored in an InternalTexture
  14798. */
  14799. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  14800. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  14801. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  14802. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  14803. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  14804. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14805. }
  14806. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  14807. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  14808. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14809. }
  14810. var gl = this._gl;
  14811. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  14812. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14813. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  14814. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  14815. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14816. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  14817. }
  14818. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  14819. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  14820. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14821. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14822. for (var face = 0; face < 6; face++) {
  14823. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), size, size, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  14824. }
  14825. // Create the framebuffer
  14826. var framebuffer = gl.createFramebuffer();
  14827. this.bindUnboundFramebuffer(framebuffer);
  14828. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  14829. // MipMaps
  14830. if (fullOptions.generateMipMaps) {
  14831. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14832. }
  14833. // Unbind
  14834. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14835. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  14836. this.bindUnboundFramebuffer(null);
  14837. texture._framebuffer = framebuffer;
  14838. texture.width = size;
  14839. texture.height = size;
  14840. texture.isReady = true;
  14841. texture.isCube = true;
  14842. texture.samples = 1;
  14843. texture.generateMipMaps = fullOptions.generateMipMaps;
  14844. texture.samplingMode = fullOptions.samplingMode;
  14845. texture.type = fullOptions.type;
  14846. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  14847. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  14848. this._internalTexturesCache.push(texture);
  14849. return texture;
  14850. };
  14851. /**
  14852. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  14853. * @param rootUrl defines the url where the file to load is located
  14854. * @param scene defines the current scene
  14855. * @param scale defines scale to apply to the mip map selection
  14856. * @param offset defines offset to apply to the mip map selection
  14857. * @param onLoad defines an optional callback raised when the texture is loaded
  14858. * @param onError defines an optional callback raised if there is an issue to load the texture
  14859. * @param format defines the format of the data
  14860. * @param forcedExtension defines the extension to use to pick the right loader
  14861. * @returns the cube texture as an InternalTexture
  14862. */
  14863. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  14864. var _this = this;
  14865. if (onLoad === void 0) { onLoad = null; }
  14866. if (onError === void 0) { onError = null; }
  14867. if (forcedExtension === void 0) { forcedExtension = null; }
  14868. var callback = function (loadData) {
  14869. if (!loadData) {
  14870. if (onLoad) {
  14871. onLoad(null);
  14872. }
  14873. return;
  14874. }
  14875. var texture = loadData.texture;
  14876. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  14877. texture._lodGenerationScale = scale;
  14878. texture._lodGenerationOffset = offset;
  14879. if (_this._caps.textureLOD) {
  14880. // Do not add extra process if texture lod is supported.
  14881. if (onLoad) {
  14882. onLoad(texture);
  14883. }
  14884. return;
  14885. }
  14886. var mipSlices = 3;
  14887. var gl = _this._gl;
  14888. var width = loadData.width;
  14889. if (!width) {
  14890. return;
  14891. }
  14892. var textures = [];
  14893. for (var i = 0; i < mipSlices; i++) {
  14894. //compute LOD from even spacing in smoothness (matching shader calculation)
  14895. var smoothness = i / (mipSlices - 1);
  14896. var roughness = 1 - smoothness;
  14897. var minLODIndex = offset; // roughness = 0
  14898. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  14899. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  14900. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  14901. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14902. glTextureFromLod.isCube = true;
  14903. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  14904. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14905. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14906. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14907. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14908. if (loadData.isDDS) {
  14909. var info = loadData.info;
  14910. var data = loadData.data;
  14911. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14912. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  14913. }
  14914. else {
  14915. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  14916. }
  14917. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14918. // Wrap in a base texture for easy binding.
  14919. var lodTexture = new BABYLON.BaseTexture(scene);
  14920. lodTexture.isCube = true;
  14921. lodTexture._texture = glTextureFromLod;
  14922. glTextureFromLod.isReady = true;
  14923. textures.push(lodTexture);
  14924. }
  14925. texture._lodTextureHigh = textures[2];
  14926. texture._lodTextureMid = textures[1];
  14927. texture._lodTextureLow = textures[0];
  14928. if (onLoad) {
  14929. onLoad(texture);
  14930. }
  14931. };
  14932. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  14933. };
  14934. /**
  14935. * Creates a cube texture
  14936. * @param rootUrl defines the url where the files to load is located
  14937. * @param scene defines the current scene
  14938. * @param files defines the list of files to load (1 per face)
  14939. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  14940. * @param onLoad defines an optional callback raised when the texture is loaded
  14941. * @param onError defines an optional callback raised if there is an issue to load the texture
  14942. * @param format defines the format of the data
  14943. * @param forcedExtension defines the extension to use to pick the right loader
  14944. * @returns the cube texture as an InternalTexture
  14945. */
  14946. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  14947. var _this = this;
  14948. if (onLoad === void 0) { onLoad = null; }
  14949. if (onError === void 0) { onError = null; }
  14950. if (forcedExtension === void 0) { forcedExtension = null; }
  14951. var gl = this._gl;
  14952. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  14953. texture.isCube = true;
  14954. texture.url = rootUrl;
  14955. texture.generateMipMaps = !noMipmap;
  14956. if (!this._doNotHandleContextLost) {
  14957. texture._extension = forcedExtension;
  14958. texture._files = files;
  14959. }
  14960. var isKTX = false;
  14961. var isDDS = false;
  14962. var lastDot = rootUrl.lastIndexOf('.');
  14963. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  14964. if (this._textureFormatInUse) {
  14965. extension = this._textureFormatInUse;
  14966. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  14967. isKTX = true;
  14968. }
  14969. else {
  14970. isDDS = (extension === ".dds");
  14971. }
  14972. var onerror = function (request, exception) {
  14973. if (onError && request) {
  14974. onError(request.status + " " + request.statusText, exception);
  14975. }
  14976. };
  14977. if (isKTX) {
  14978. this._loadFile(rootUrl, function (data) {
  14979. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  14980. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  14981. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14982. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  14983. ktx.uploadLevels(_this._gl, !noMipmap);
  14984. _this.setCubeMapTextureParams(gl, loadMipmap);
  14985. texture.width = ktx.pixelWidth;
  14986. texture.height = ktx.pixelHeight;
  14987. texture.isReady = true;
  14988. }, undefined, undefined, true, onerror);
  14989. }
  14990. else if (isDDS) {
  14991. if (files && files.length === 6) {
  14992. this._cascadeLoadFiles(scene, function (imgs) {
  14993. var info;
  14994. var loadMipmap = false;
  14995. var width = 0;
  14996. for (var index = 0; index < imgs.length; index++) {
  14997. var data = imgs[index];
  14998. info = BABYLON.DDSTools.GetDDSInfo(data);
  14999. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15000. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15001. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15002. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15003. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15004. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15005. }
  15006. texture.width = info.width;
  15007. texture.height = info.height;
  15008. texture.type = info.textureType;
  15009. width = info.width;
  15010. }
  15011. _this.setCubeMapTextureParams(gl, loadMipmap);
  15012. texture.isReady = true;
  15013. if (onLoad) {
  15014. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15015. }
  15016. }, files, onError);
  15017. }
  15018. else {
  15019. this._loadFile(rootUrl, function (data) {
  15020. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15021. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15022. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15023. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15024. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15025. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15026. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15027. }
  15028. _this.setCubeMapTextureParams(gl, loadMipmap);
  15029. texture.width = info.width;
  15030. texture.height = info.height;
  15031. texture.isReady = true;
  15032. texture.type = info.textureType;
  15033. if (onLoad) {
  15034. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15035. }
  15036. }, undefined, undefined, true, onerror);
  15037. }
  15038. }
  15039. else {
  15040. if (!files) {
  15041. throw new Error("Cannot load cubemap because files were not defined");
  15042. }
  15043. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15044. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15045. var height = width;
  15046. _this._prepareWorkingCanvas();
  15047. if (!_this._workingCanvas || !_this._workingContext) {
  15048. return;
  15049. }
  15050. _this._workingCanvas.width = width;
  15051. _this._workingCanvas.height = height;
  15052. var faces = [
  15053. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15054. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15055. ];
  15056. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15057. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15058. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15059. for (var index = 0; index < faces.length; index++) {
  15060. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15061. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15062. }
  15063. if (!noMipmap) {
  15064. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15065. }
  15066. _this.setCubeMapTextureParams(gl, !noMipmap);
  15067. texture.width = width;
  15068. texture.height = height;
  15069. texture.isReady = true;
  15070. if (format) {
  15071. texture.format = format;
  15072. }
  15073. texture.onLoadedObservable.notifyObservers(texture);
  15074. texture.onLoadedObservable.clear();
  15075. if (onLoad) {
  15076. onLoad();
  15077. }
  15078. }, files, onError);
  15079. }
  15080. this._internalTexturesCache.push(texture);
  15081. return texture;
  15082. };
  15083. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15084. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15085. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15086. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15087. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15088. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15089. // this.resetTextureCache();
  15090. };
  15091. /**
  15092. * Update a raw cube texture
  15093. * @param texture defines the texture to udpdate
  15094. * @param data defines the data to store
  15095. * @param format defines the data format
  15096. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15097. * @param invertY defines if data must be stored with Y axis inverted
  15098. * @param compression defines the compression used (null by default)
  15099. * @param level defines which level of the texture to update
  15100. */
  15101. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15102. if (compression === void 0) { compression = null; }
  15103. if (level === void 0) { level = 0; }
  15104. texture._bufferViewArray = data;
  15105. texture.format = format;
  15106. texture.type = type;
  15107. texture.invertY = invertY;
  15108. texture._compression = compression;
  15109. var gl = this._gl;
  15110. var textureType = this._getWebGLTextureType(type);
  15111. var internalFormat = this._getInternalFormat(format);
  15112. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15113. var needConversion = false;
  15114. if (internalFormat === gl.RGB) {
  15115. internalFormat = gl.RGBA;
  15116. needConversion = true;
  15117. }
  15118. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15119. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15120. if (texture.width % 4 !== 0) {
  15121. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15122. }
  15123. // Data are known to be in +X +Y +Z -X -Y -Z
  15124. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15125. var faceData = data[faceIndex];
  15126. if (compression) {
  15127. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15128. }
  15129. else {
  15130. if (needConversion) {
  15131. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15132. }
  15133. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15134. }
  15135. }
  15136. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15137. if (isPot && texture.generateMipMaps && level === 0) {
  15138. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15139. }
  15140. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15141. // this.resetTextureCache();
  15142. texture.isReady = true;
  15143. };
  15144. /**
  15145. * Creates a new raw cube texture
  15146. * @param data defines the array of data to use to create each face
  15147. * @param size defines the size of the textures
  15148. * @param format defines the format of the data
  15149. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15150. * @param generateMipMaps defines if the engine should generate the mip levels
  15151. * @param invertY defines if data must be stored with Y axis inverted
  15152. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15153. * @param compression defines the compression used (null by default)
  15154. * @returns the cube texture as an InternalTexture
  15155. */
  15156. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15157. if (compression === void 0) { compression = null; }
  15158. var gl = this._gl;
  15159. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15160. texture.isCube = true;
  15161. texture.generateMipMaps = generateMipMaps;
  15162. texture.format = format;
  15163. texture.type = type;
  15164. if (!this._doNotHandleContextLost) {
  15165. texture._bufferViewArray = data;
  15166. }
  15167. var textureType = this._getWebGLTextureType(type);
  15168. var internalFormat = this._getInternalFormat(format);
  15169. if (internalFormat === gl.RGB) {
  15170. internalFormat = gl.RGBA;
  15171. }
  15172. var width = size;
  15173. var height = width;
  15174. texture.width = width;
  15175. texture.height = height;
  15176. // Double check on POT to generate Mips.
  15177. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15178. if (!isPot) {
  15179. generateMipMaps = false;
  15180. }
  15181. // Upload data if needed. The texture won't be ready until then.
  15182. if (data) {
  15183. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15184. }
  15185. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15186. // Filters
  15187. if (data && generateMipMaps) {
  15188. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15189. }
  15190. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15191. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15192. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15193. }
  15194. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15195. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15196. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15197. }
  15198. else {
  15199. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15200. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15201. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15202. }
  15203. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15204. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15205. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15206. return texture;
  15207. };
  15208. /**
  15209. * Creates a new raw cube texture from a specified url
  15210. * @param url defines the url where the data is located
  15211. * @param scene defines the current scene
  15212. * @param size defines the size of the textures
  15213. * @param format defines the format of the data
  15214. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15215. * @param noMipmap defines if the engine should avoid generating the mip levels
  15216. * @param callback defines a callback used to extract texture data from loaded data
  15217. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15218. * @param onLoad defines a callback called when texture is loaded
  15219. * @param onError defines a callback called if there is an error
  15220. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15221. * @param invertY defines if data must be stored with Y axis inverted
  15222. * @returns the cube texture as an InternalTexture
  15223. */
  15224. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15225. var _this = this;
  15226. if (onLoad === void 0) { onLoad = null; }
  15227. if (onError === void 0) { onError = null; }
  15228. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15229. if (invertY === void 0) { invertY = false; }
  15230. var gl = this._gl;
  15231. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15232. scene._addPendingData(texture);
  15233. texture.url = url;
  15234. this._internalTexturesCache.push(texture);
  15235. var onerror = function (request, exception) {
  15236. scene._removePendingData(texture);
  15237. if (onError && request) {
  15238. onError(request.status + " " + request.statusText, exception);
  15239. }
  15240. };
  15241. var internalCallback = function (data) {
  15242. var width = texture.width;
  15243. var faceDataArrays = callback(data);
  15244. if (!faceDataArrays) {
  15245. return;
  15246. }
  15247. if (mipmapGenerator) {
  15248. var textureType = _this._getWebGLTextureType(type);
  15249. var internalFormat = _this._getInternalFormat(format);
  15250. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15251. var needConversion = false;
  15252. if (internalFormat === gl.RGB) {
  15253. internalFormat = gl.RGBA;
  15254. needConversion = true;
  15255. }
  15256. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15257. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15258. var mipData = mipmapGenerator(faceDataArrays);
  15259. for (var level = 0; level < mipData.length; level++) {
  15260. var mipSize = width >> level;
  15261. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15262. var mipFaceData = mipData[level][faceIndex];
  15263. if (needConversion) {
  15264. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15265. }
  15266. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15267. }
  15268. }
  15269. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15270. }
  15271. else {
  15272. texture.generateMipMaps = !noMipmap;
  15273. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15274. }
  15275. texture.isReady = true;
  15276. // this.resetTextureCache();
  15277. scene._removePendingData(texture);
  15278. if (onLoad) {
  15279. onLoad();
  15280. }
  15281. };
  15282. this._loadFile(url, function (data) {
  15283. internalCallback(data);
  15284. }, undefined, scene.database, true, onerror);
  15285. return texture;
  15286. };
  15287. ;
  15288. /**
  15289. * Update a raw 3D texture
  15290. * @param texture defines the texture to update
  15291. * @param data defines the data to store
  15292. * @param format defines the data format
  15293. * @param invertY defines if data must be stored with Y axis inverted
  15294. * @param compression defines the used compression (can be null)
  15295. */
  15296. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  15297. if (compression === void 0) { compression = null; }
  15298. var internalFormat = this._getInternalFormat(format);
  15299. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15300. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15301. if (!this._doNotHandleContextLost) {
  15302. texture._bufferView = data;
  15303. texture.format = format;
  15304. texture.invertY = invertY;
  15305. texture._compression = compression;
  15306. }
  15307. if (texture.width % 4 !== 0) {
  15308. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15309. }
  15310. if (compression && data) {
  15311. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  15312. }
  15313. else {
  15314. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  15315. }
  15316. if (texture.generateMipMaps) {
  15317. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15318. }
  15319. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15320. // this.resetTextureCache();
  15321. texture.isReady = true;
  15322. };
  15323. /**
  15324. * Creates a new raw 3D texture
  15325. * @param data defines the data used to create the texture
  15326. * @param width defines the width of the texture
  15327. * @param height defines the height of the texture
  15328. * @param depth defines the depth of the texture
  15329. * @param format defines the format of the texture
  15330. * @param generateMipMaps defines if the engine must generate mip levels
  15331. * @param invertY defines if data must be stored with Y axis inverted
  15332. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15333. * @param compression defines the compressed used (can be null)
  15334. * @returns a new raw 3D texture (stored in an InternalTexture)
  15335. */
  15336. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  15337. if (compression === void 0) { compression = null; }
  15338. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  15339. texture.baseWidth = width;
  15340. texture.baseHeight = height;
  15341. texture.baseDepth = depth;
  15342. texture.width = width;
  15343. texture.height = height;
  15344. texture.depth = depth;
  15345. texture.format = format;
  15346. texture.generateMipMaps = generateMipMaps;
  15347. texture.samplingMode = samplingMode;
  15348. texture.is3D = true;
  15349. if (!this._doNotHandleContextLost) {
  15350. texture._bufferView = data;
  15351. }
  15352. this.updateRawTexture3D(texture, data, format, invertY, compression);
  15353. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15354. // Filters
  15355. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  15356. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15357. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15358. if (generateMipMaps) {
  15359. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15360. }
  15361. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15362. this._internalTexturesCache.push(texture);
  15363. return texture;
  15364. };
  15365. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  15366. var gl = this._gl;
  15367. if (!gl) {
  15368. return;
  15369. }
  15370. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  15371. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15372. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15373. if (!noMipmap && !isCompressed) {
  15374. gl.generateMipmap(gl.TEXTURE_2D);
  15375. }
  15376. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15377. // this.resetTextureCache();
  15378. if (scene) {
  15379. scene._removePendingData(texture);
  15380. }
  15381. texture.onLoadedObservable.notifyObservers(texture);
  15382. texture.onLoadedObservable.clear();
  15383. };
  15384. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  15385. var _this = this;
  15386. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15387. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  15388. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  15389. var gl = this._gl;
  15390. if (!gl) {
  15391. return;
  15392. }
  15393. if (!texture._webGLTexture) {
  15394. // this.resetTextureCache();
  15395. if (scene) {
  15396. scene._removePendingData(texture);
  15397. }
  15398. return;
  15399. }
  15400. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15401. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15402. texture.baseWidth = width;
  15403. texture.baseHeight = height;
  15404. texture.width = potWidth;
  15405. texture.height = potHeight;
  15406. texture.isReady = true;
  15407. if (processFunction(potWidth, potHeight, function () {
  15408. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  15409. })) {
  15410. // Returning as texture needs extra async steps
  15411. return;
  15412. }
  15413. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  15414. };
  15415. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  15416. // Create new RGBA data container.
  15417. var rgbaData;
  15418. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  15419. rgbaData = new Float32Array(width * height * 4);
  15420. }
  15421. else {
  15422. rgbaData = new Uint32Array(width * height * 4);
  15423. }
  15424. // Convert each pixel.
  15425. for (var x = 0; x < width; x++) {
  15426. for (var y = 0; y < height; y++) {
  15427. var index = (y * width + x) * 3;
  15428. var newIndex = (y * width + x) * 4;
  15429. // Map Old Value to new value.
  15430. rgbaData[newIndex + 0] = rgbData[index + 0];
  15431. rgbaData[newIndex + 1] = rgbData[index + 1];
  15432. rgbaData[newIndex + 2] = rgbData[index + 2];
  15433. // Add fully opaque alpha channel.
  15434. rgbaData[newIndex + 3] = 1;
  15435. }
  15436. }
  15437. return rgbaData;
  15438. };
  15439. /** @ignore */
  15440. Engine.prototype._releaseFramebufferObjects = function (texture) {
  15441. var gl = this._gl;
  15442. if (texture._framebuffer) {
  15443. gl.deleteFramebuffer(texture._framebuffer);
  15444. texture._framebuffer = null;
  15445. }
  15446. if (texture._depthStencilBuffer) {
  15447. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15448. texture._depthStencilBuffer = null;
  15449. }
  15450. if (texture._MSAAFramebuffer) {
  15451. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15452. texture._MSAAFramebuffer = null;
  15453. }
  15454. if (texture._MSAARenderBuffer) {
  15455. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15456. texture._MSAARenderBuffer = null;
  15457. }
  15458. };
  15459. /** @ignore */
  15460. Engine.prototype._releaseTexture = function (texture) {
  15461. var gl = this._gl;
  15462. this._releaseFramebufferObjects(texture);
  15463. gl.deleteTexture(texture._webGLTexture);
  15464. // Unbind channels
  15465. this.unbindAllTextures();
  15466. var index = this._internalTexturesCache.indexOf(texture);
  15467. if (index !== -1) {
  15468. this._internalTexturesCache.splice(index, 1);
  15469. }
  15470. // Integrated fixed lod samplers.
  15471. if (texture._lodTextureHigh) {
  15472. texture._lodTextureHigh.dispose();
  15473. }
  15474. if (texture._lodTextureMid) {
  15475. texture._lodTextureMid.dispose();
  15476. }
  15477. if (texture._lodTextureLow) {
  15478. texture._lodTextureLow.dispose();
  15479. }
  15480. // Set output texture of post process to null if the texture has been released/disposed
  15481. this.scenes.forEach(function (scene) {
  15482. scene.postProcesses.forEach(function (postProcess) {
  15483. if (postProcess._outputTexture == texture) {
  15484. postProcess._outputTexture = null;
  15485. }
  15486. });
  15487. scene.cameras.forEach(function (camera) {
  15488. camera._postProcesses.forEach(function (postProcess) {
  15489. if (postProcess) {
  15490. if (postProcess._outputTexture == texture) {
  15491. postProcess._outputTexture = null;
  15492. }
  15493. }
  15494. });
  15495. });
  15496. });
  15497. };
  15498. Engine.prototype.setProgram = function (program) {
  15499. if (this._currentProgram !== program) {
  15500. this._gl.useProgram(program);
  15501. this._currentProgram = program;
  15502. }
  15503. };
  15504. /**
  15505. * Binds an effect to the webGL context
  15506. * @param effect defines the effect to bind
  15507. */
  15508. Engine.prototype.bindSamplers = function (effect) {
  15509. this.setProgram(effect.getProgram());
  15510. var samplers = effect.getSamplers();
  15511. for (var index = 0; index < samplers.length; index++) {
  15512. var uniform = effect.getUniform(samplers[index]);
  15513. if (uniform) {
  15514. this._boundUniforms[index] = uniform;
  15515. }
  15516. }
  15517. this._currentEffect = null;
  15518. };
  15519. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  15520. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  15521. return;
  15522. }
  15523. // Remove
  15524. this._linkTrackers(internalTexture.previous, internalTexture.next);
  15525. // Bind last to it
  15526. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  15527. // Bind to dummy
  15528. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  15529. };
  15530. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  15531. if (!internalTexture) {
  15532. return -1;
  15533. }
  15534. internalTexture._initialSlot = channel;
  15535. if (this.disableTextureBindingOptimization) {
  15536. if (channel !== internalTexture._designatedSlot) {
  15537. this._textureCollisions.addCount(1, false);
  15538. }
  15539. }
  15540. else {
  15541. if (channel !== internalTexture._designatedSlot) {
  15542. if (internalTexture._designatedSlot > -1) {
  15543. return internalTexture._designatedSlot;
  15544. }
  15545. else {
  15546. // No slot for this texture, let's pick a new one (if we find a free slot)
  15547. if (this._nextFreeTextureSlots.length) {
  15548. return this._nextFreeTextureSlots[0];
  15549. }
  15550. // We need to recycle the oldest bound texture, sorry.
  15551. this._textureCollisions.addCount(1, false);
  15552. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  15553. }
  15554. }
  15555. }
  15556. return channel;
  15557. };
  15558. Engine.prototype._linkTrackers = function (previous, next) {
  15559. previous.next = next;
  15560. next.previous = previous;
  15561. };
  15562. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  15563. var currentSlot = internalTexture._designatedSlot;
  15564. if (currentSlot === -1) {
  15565. return -1;
  15566. }
  15567. internalTexture._designatedSlot = -1;
  15568. if (this.disableTextureBindingOptimization) {
  15569. return -1;
  15570. }
  15571. // Remove from bound list
  15572. this._linkTrackers(internalTexture.previous, internalTexture.next);
  15573. // Free the slot
  15574. this._boundTexturesCache[currentSlot] = null;
  15575. this._nextFreeTextureSlots.push(currentSlot);
  15576. return currentSlot;
  15577. };
  15578. Engine.prototype._activateCurrentTexture = function () {
  15579. if (this._currentTextureChannel !== this._activeChannel) {
  15580. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  15581. this._currentTextureChannel = this._activeChannel;
  15582. }
  15583. };
  15584. /** @ignore */
  15585. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  15586. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  15587. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  15588. this._activeChannel = texture._designatedSlot;
  15589. }
  15590. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  15591. var isTextureForRendering = texture && texture._initialSlot > -1;
  15592. if (currentTextureBound !== texture) {
  15593. if (currentTextureBound) {
  15594. this._removeDesignatedSlot(currentTextureBound);
  15595. }
  15596. this._activateCurrentTexture();
  15597. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  15598. this._boundTexturesCache[this._activeChannel] = texture;
  15599. if (texture) {
  15600. if (!this.disableTextureBindingOptimization) {
  15601. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  15602. if (slotIndex > -1) {
  15603. this._nextFreeTextureSlots.splice(slotIndex, 1);
  15604. }
  15605. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  15606. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  15607. }
  15608. texture._designatedSlot = this._activeChannel;
  15609. }
  15610. }
  15611. else if (forTextureDataUpdate) {
  15612. this._activateCurrentTexture();
  15613. }
  15614. if (isTextureForRendering && !forTextureDataUpdate) {
  15615. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  15616. }
  15617. };
  15618. /** @ignore */
  15619. Engine.prototype._bindTexture = function (channel, texture) {
  15620. if (channel < 0) {
  15621. return;
  15622. }
  15623. if (texture) {
  15624. channel = this._getCorrectTextureChannel(channel, texture);
  15625. }
  15626. this._activeChannel = channel;
  15627. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  15628. };
  15629. /**
  15630. * Sets a texture to the webGL context from a postprocess
  15631. * @param channel defines the channel to use
  15632. * @param postProcess defines the source postprocess
  15633. */
  15634. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  15635. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  15636. };
  15637. /**
  15638. * Binds the output of the passed in post process to the texture channel specified
  15639. * @param channel The channel the texture should be bound to
  15640. * @param postProcess The post process which's output should be bound
  15641. */
  15642. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  15643. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  15644. };
  15645. /**
  15646. * Unbind all textures from the webGL context
  15647. */
  15648. Engine.prototype.unbindAllTextures = function () {
  15649. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  15650. this._activeChannel = channel;
  15651. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15652. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15653. if (this.webGLVersion > 1) {
  15654. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15655. }
  15656. }
  15657. };
  15658. /**
  15659. * Sets a texture to the according uniform.
  15660. * @param channel The texture channel
  15661. * @param uniform The uniform to set
  15662. * @param texture The texture to apply
  15663. */
  15664. Engine.prototype.setTexture = function (channel, uniform, texture) {
  15665. if (channel < 0) {
  15666. return;
  15667. }
  15668. if (uniform) {
  15669. this._boundUniforms[channel] = uniform;
  15670. }
  15671. this._setTexture(channel, texture);
  15672. };
  15673. /**
  15674. * Sets a depth stencil texture from a render target to the according uniform.
  15675. * @param channel The texture channel
  15676. * @param uniform The uniform to set
  15677. * @param texture The render target texture containing the depth stencil texture to apply
  15678. */
  15679. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  15680. if (channel < 0) {
  15681. return;
  15682. }
  15683. if (uniform) {
  15684. this._boundUniforms[channel] = uniform;
  15685. }
  15686. if (!texture || !texture.depthStencilTexture) {
  15687. this._setTexture(channel, null);
  15688. }
  15689. else {
  15690. this._setTexture(channel, texture, false, true);
  15691. }
  15692. };
  15693. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  15694. var uniform = this._boundUniforms[sourceSlot];
  15695. if (uniform._currentState === destination) {
  15696. return;
  15697. }
  15698. this._gl.uniform1i(uniform, destination);
  15699. uniform._currentState = destination;
  15700. };
  15701. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  15702. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  15703. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  15704. // Not ready?
  15705. if (!texture) {
  15706. if (this._boundTexturesCache[channel] != null) {
  15707. this._activeChannel = channel;
  15708. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15709. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15710. if (this.webGLVersion > 1) {
  15711. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15712. }
  15713. }
  15714. return false;
  15715. }
  15716. // Video
  15717. if (texture.video) {
  15718. this._activeChannel = channel;
  15719. texture.update();
  15720. }
  15721. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  15722. texture.delayLoad();
  15723. return false;
  15724. }
  15725. var internalTexture;
  15726. if (depthStencilTexture) {
  15727. internalTexture = texture.depthStencilTexture;
  15728. }
  15729. else if (texture.isReady()) {
  15730. internalTexture = texture.getInternalTexture();
  15731. }
  15732. else if (texture.isCube) {
  15733. internalTexture = this.emptyCubeTexture;
  15734. }
  15735. else if (texture.is3D) {
  15736. internalTexture = this.emptyTexture3D;
  15737. }
  15738. else {
  15739. internalTexture = this.emptyTexture;
  15740. }
  15741. if (!isPartOfTextureArray) {
  15742. channel = this._getCorrectTextureChannel(channel, internalTexture);
  15743. }
  15744. if (this._boundTexturesCache[channel] === internalTexture) {
  15745. this._moveBoundTextureOnTop(internalTexture);
  15746. if (!isPartOfTextureArray) {
  15747. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  15748. }
  15749. return false;
  15750. }
  15751. this._activeChannel = channel;
  15752. if (internalTexture && internalTexture.is3D) {
  15753. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  15754. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  15755. internalTexture._cachedWrapU = texture.wrapU;
  15756. switch (texture.wrapU) {
  15757. case BABYLON.Texture.WRAP_ADDRESSMODE:
  15758. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  15759. break;
  15760. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  15761. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  15762. break;
  15763. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  15764. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  15765. break;
  15766. }
  15767. }
  15768. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  15769. internalTexture._cachedWrapV = texture.wrapV;
  15770. switch (texture.wrapV) {
  15771. case BABYLON.Texture.WRAP_ADDRESSMODE:
  15772. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  15773. break;
  15774. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  15775. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  15776. break;
  15777. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  15778. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  15779. break;
  15780. }
  15781. }
  15782. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  15783. internalTexture._cachedWrapR = texture.wrapR;
  15784. switch (texture.wrapR) {
  15785. case BABYLON.Texture.WRAP_ADDRESSMODE:
  15786. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  15787. break;
  15788. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  15789. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  15790. break;
  15791. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  15792. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  15793. break;
  15794. }
  15795. }
  15796. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  15797. }
  15798. else if (internalTexture && internalTexture.isCube) {
  15799. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  15800. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  15801. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  15802. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  15803. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  15804. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  15805. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  15806. }
  15807. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  15808. }
  15809. else {
  15810. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  15811. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  15812. internalTexture._cachedWrapU = texture.wrapU;
  15813. switch (texture.wrapU) {
  15814. case BABYLON.Texture.WRAP_ADDRESSMODE:
  15815. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  15816. break;
  15817. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  15818. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  15819. break;
  15820. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  15821. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  15822. break;
  15823. }
  15824. }
  15825. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  15826. internalTexture._cachedWrapV = texture.wrapV;
  15827. switch (texture.wrapV) {
  15828. case BABYLON.Texture.WRAP_ADDRESSMODE:
  15829. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  15830. break;
  15831. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  15832. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  15833. break;
  15834. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  15835. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  15836. break;
  15837. }
  15838. }
  15839. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  15840. }
  15841. return true;
  15842. };
  15843. /**
  15844. * Sets an array of texture to the webGL context
  15845. * @param channel defines the channel where the texture array must be set
  15846. * @param uniform defines the associated uniform location
  15847. * @param textures defines the array of textures to bind
  15848. */
  15849. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  15850. if (channel < 0 || !uniform) {
  15851. return;
  15852. }
  15853. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  15854. this._textureUnits = new Int32Array(textures.length);
  15855. }
  15856. for (var i = 0; i < textures.length; i++) {
  15857. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  15858. }
  15859. this._gl.uniform1iv(uniform, this._textureUnits);
  15860. for (var index = 0; index < textures.length; index++) {
  15861. this._setTexture(this._textureUnits[index], textures[index], true);
  15862. }
  15863. };
  15864. /** @ignore */
  15865. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  15866. var internalTexture = texture.getInternalTexture();
  15867. if (!internalTexture) {
  15868. return;
  15869. }
  15870. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  15871. var value = texture.anisotropicFilteringLevel;
  15872. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  15873. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  15874. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  15875. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  15876. }
  15877. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  15878. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  15879. internalTexture._cachedAnisotropicFilteringLevel = value;
  15880. }
  15881. };
  15882. /**
  15883. * Reads pixels from the current frame buffer. Please note that this function can be slow
  15884. * @param x defines the x coordinate of the rectangle where pixels must be read
  15885. * @param y defines the y coordinate of the rectangle where pixels must be read
  15886. * @param width defines the width of the rectangle where pixels must be read
  15887. * @param height defines the height of the rectangle where pixels must be read
  15888. * @returns a Uint8Array containing RGBA colors
  15889. */
  15890. Engine.prototype.readPixels = function (x, y, width, height) {
  15891. var data = new Uint8Array(height * width * 4);
  15892. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  15893. return data;
  15894. };
  15895. /**
  15896. * Add an externaly attached data from its key.
  15897. * This method call will fail and return false, if such key already exists.
  15898. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  15899. * @param key the unique key that identifies the data
  15900. * @param data the data object to associate to the key for this Engine instance
  15901. * @return true if no such key were already present and the data was added successfully, false otherwise
  15902. */
  15903. Engine.prototype.addExternalData = function (key, data) {
  15904. if (!this._externalData) {
  15905. this._externalData = new BABYLON.StringDictionary();
  15906. }
  15907. return this._externalData.add(key, data);
  15908. };
  15909. /**
  15910. * Get an externaly attached data from its key
  15911. * @param key the unique key that identifies the data
  15912. * @return the associated data, if present (can be null), or undefined if not present
  15913. */
  15914. Engine.prototype.getExternalData = function (key) {
  15915. if (!this._externalData) {
  15916. this._externalData = new BABYLON.StringDictionary();
  15917. }
  15918. return this._externalData.get(key);
  15919. };
  15920. /**
  15921. * Get an externaly attached data from its key, create it using a factory if it's not already present
  15922. * @param key the unique key that identifies the data
  15923. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  15924. * @return the associated data, can be null if the factory returned null.
  15925. */
  15926. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  15927. if (!this._externalData) {
  15928. this._externalData = new BABYLON.StringDictionary();
  15929. }
  15930. return this._externalData.getOrAddWithFactory(key, factory);
  15931. };
  15932. /**
  15933. * Remove an externaly attached data from the Engine instance
  15934. * @param key the unique key that identifies the data
  15935. * @return true if the data was successfully removed, false if it doesn't exist
  15936. */
  15937. Engine.prototype.removeExternalData = function (key) {
  15938. if (!this._externalData) {
  15939. this._externalData = new BABYLON.StringDictionary();
  15940. }
  15941. return this._externalData.remove(key);
  15942. };
  15943. /**
  15944. * Unbind all vertex attributes from the webGL context
  15945. */
  15946. Engine.prototype.unbindAllAttributes = function () {
  15947. if (this._mustWipeVertexAttributes) {
  15948. this._mustWipeVertexAttributes = false;
  15949. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  15950. this._gl.disableVertexAttribArray(i);
  15951. this._vertexAttribArraysEnabled[i] = false;
  15952. this._currentBufferPointers[i].active = false;
  15953. }
  15954. return;
  15955. }
  15956. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  15957. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  15958. continue;
  15959. }
  15960. this._gl.disableVertexAttribArray(i);
  15961. this._vertexAttribArraysEnabled[i] = false;
  15962. this._currentBufferPointers[i].active = false;
  15963. }
  15964. };
  15965. /**
  15966. * Force the engine to release all cached effects. This means that next effect compilation will have to be done completely even if a similar effect was already compiled
  15967. */
  15968. Engine.prototype.releaseEffects = function () {
  15969. for (var name in this._compiledEffects) {
  15970. this._deleteProgram(this._compiledEffects[name]._program);
  15971. }
  15972. this._compiledEffects = {};
  15973. };
  15974. /**
  15975. * Dispose and release all associated resources
  15976. */
  15977. Engine.prototype.dispose = function () {
  15978. this.hideLoadingUI();
  15979. this.stopRenderLoop();
  15980. // Release postProcesses
  15981. while (this.postProcesses.length) {
  15982. this.postProcesses[0].dispose();
  15983. }
  15984. // Empty texture
  15985. if (this._emptyTexture) {
  15986. this._releaseTexture(this._emptyTexture);
  15987. this._emptyTexture = null;
  15988. }
  15989. if (this._emptyCubeTexture) {
  15990. this._releaseTexture(this._emptyCubeTexture);
  15991. this._emptyCubeTexture = null;
  15992. }
  15993. // Rescale PP
  15994. if (this._rescalePostProcess) {
  15995. this._rescalePostProcess.dispose();
  15996. }
  15997. // Release scenes
  15998. while (this.scenes.length) {
  15999. this.scenes[0].dispose();
  16000. }
  16001. // Release audio engine
  16002. if (Engine.audioEngine) {
  16003. Engine.audioEngine.dispose();
  16004. }
  16005. // Release effects
  16006. this.releaseEffects();
  16007. // Unbind
  16008. this.unbindAllAttributes();
  16009. this._boundUniforms = [];
  16010. if (this._dummyFramebuffer) {
  16011. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16012. }
  16013. //WebVR
  16014. this.disableVR();
  16015. // Events
  16016. if (BABYLON.Tools.IsWindowObjectExist()) {
  16017. window.removeEventListener("blur", this._onBlur);
  16018. window.removeEventListener("focus", this._onFocus);
  16019. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16020. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16021. if (this._renderingCanvas) {
  16022. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16023. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16024. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16025. if (!this._doNotHandleContextLost) {
  16026. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16027. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16028. }
  16029. }
  16030. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16031. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16032. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16033. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16034. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16035. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16036. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16037. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16038. if (this._onVrDisplayConnect) {
  16039. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16040. if (this._onVrDisplayDisconnect) {
  16041. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16042. }
  16043. if (this._onVrDisplayPresentChange) {
  16044. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16045. }
  16046. this._onVrDisplayConnect = null;
  16047. this._onVrDisplayDisconnect = null;
  16048. }
  16049. }
  16050. // Remove from Instances
  16051. var index = Engine.Instances.indexOf(this);
  16052. if (index >= 0) {
  16053. Engine.Instances.splice(index, 1);
  16054. }
  16055. this._workingCanvas = null;
  16056. this._workingContext = null;
  16057. this._currentBufferPointers = [];
  16058. this._renderingCanvas = null;
  16059. this._currentProgram = null;
  16060. this._bindedRenderFunction = null;
  16061. this.onResizeObservable.clear();
  16062. this.onCanvasBlurObservable.clear();
  16063. this.onCanvasFocusObservable.clear();
  16064. this.onCanvasPointerOutObservable.clear();
  16065. this.onBeginFrameObservable.clear();
  16066. this.onEndFrameObservable.clear();
  16067. BABYLON.Effect.ResetCache();
  16068. // Abort active requests
  16069. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16070. var request = _a[_i];
  16071. request.abort();
  16072. }
  16073. };
  16074. // Loading screen
  16075. /**
  16076. * Display the loading screen
  16077. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16078. */
  16079. Engine.prototype.displayLoadingUI = function () {
  16080. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16081. return;
  16082. }
  16083. var loadingScreen = this.loadingScreen;
  16084. if (loadingScreen) {
  16085. loadingScreen.displayLoadingUI();
  16086. }
  16087. };
  16088. /**
  16089. * Hide the loading screen
  16090. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16091. */
  16092. Engine.prototype.hideLoadingUI = function () {
  16093. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16094. return;
  16095. }
  16096. var loadingScreen = this.loadingScreen;
  16097. if (loadingScreen) {
  16098. loadingScreen.hideLoadingUI();
  16099. }
  16100. };
  16101. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16102. /**
  16103. * Gets the current loading screen object
  16104. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16105. */
  16106. get: function () {
  16107. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16108. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16109. return this._loadingScreen;
  16110. },
  16111. /**
  16112. * Sets the current loading screen object
  16113. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16114. */
  16115. set: function (loadingScreen) {
  16116. this._loadingScreen = loadingScreen;
  16117. },
  16118. enumerable: true,
  16119. configurable: true
  16120. });
  16121. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16122. /**
  16123. * Sets the current loading screen text
  16124. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16125. */
  16126. set: function (text) {
  16127. this.loadingScreen.loadingUIText = text;
  16128. },
  16129. enumerable: true,
  16130. configurable: true
  16131. });
  16132. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16133. /**
  16134. * Sets the current loading screen background color
  16135. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16136. */
  16137. set: function (color) {
  16138. this.loadingScreen.loadingUIBackgroundColor = color;
  16139. },
  16140. enumerable: true,
  16141. configurable: true
  16142. });
  16143. /**
  16144. * Attach a new callback raised when context lost event is fired
  16145. * @param callback defines the callback to call
  16146. */
  16147. Engine.prototype.attachContextLostEvent = function (callback) {
  16148. if (this._renderingCanvas) {
  16149. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16150. }
  16151. };
  16152. /**
  16153. * Attach a new callback raised when context restored event is fired
  16154. * @param callback defines the callback to call
  16155. */
  16156. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16157. if (this._renderingCanvas) {
  16158. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16159. }
  16160. };
  16161. /**
  16162. * Gets the source code of the vertex shader associated with a specific webGL program
  16163. * @param program defines the program to use
  16164. * @returns a string containing the source code of the vertex shader associated with the program
  16165. */
  16166. Engine.prototype.getVertexShaderSource = function (program) {
  16167. var shaders = this._gl.getAttachedShaders(program);
  16168. if (!shaders) {
  16169. return null;
  16170. }
  16171. return this._gl.getShaderSource(shaders[0]);
  16172. };
  16173. /**
  16174. * Gets the source code of the fragment shader associated with a specific webGL program
  16175. * @param program defines the program to use
  16176. * @returns a string containing the source code of the fragment shader associated with the program
  16177. */
  16178. Engine.prototype.getFragmentShaderSource = function (program) {
  16179. var shaders = this._gl.getAttachedShaders(program);
  16180. if (!shaders) {
  16181. return null;
  16182. }
  16183. return this._gl.getShaderSource(shaders[1]);
  16184. };
  16185. /**
  16186. * Get the current error code of the webGL context
  16187. * @returns the error code
  16188. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16189. */
  16190. Engine.prototype.getError = function () {
  16191. return this._gl.getError();
  16192. };
  16193. // FPS
  16194. /**
  16195. * Gets the current framerate
  16196. * @returns a number representing the framerate
  16197. */
  16198. Engine.prototype.getFps = function () {
  16199. return this._fps;
  16200. };
  16201. /**
  16202. * Gets the time spent between current and previous frame
  16203. * @returns a number representing the delta time in ms
  16204. */
  16205. Engine.prototype.getDeltaTime = function () {
  16206. return this._deltaTime;
  16207. };
  16208. Engine.prototype._measureFps = function () {
  16209. this._performanceMonitor.sampleFrame();
  16210. this._fps = this._performanceMonitor.averageFPS;
  16211. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16212. };
  16213. /** @ignore */
  16214. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  16215. if (faceIndex === void 0) { faceIndex = -1; }
  16216. var gl = this._gl;
  16217. if (!this._dummyFramebuffer) {
  16218. var dummy = gl.createFramebuffer();
  16219. if (!dummy) {
  16220. throw new Error("Unable to create dummy framebuffer");
  16221. }
  16222. this._dummyFramebuffer = dummy;
  16223. }
  16224. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16225. if (faceIndex > -1) {
  16226. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  16227. }
  16228. else {
  16229. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16230. }
  16231. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16232. var buffer;
  16233. switch (readType) {
  16234. case gl.UNSIGNED_BYTE:
  16235. buffer = new Uint8Array(4 * width * height);
  16236. readType = gl.UNSIGNED_BYTE;
  16237. break;
  16238. default:
  16239. buffer = new Float32Array(4 * width * height);
  16240. readType = gl.FLOAT;
  16241. break;
  16242. }
  16243. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16244. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16245. return buffer;
  16246. };
  16247. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16248. if (this._webGLVersion > 1) {
  16249. return this._caps.colorBufferFloat;
  16250. }
  16251. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16252. };
  16253. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16254. if (this._webGLVersion > 1) {
  16255. return this._caps.colorBufferFloat;
  16256. }
  16257. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16258. };
  16259. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16260. Engine.prototype._canRenderToFramebuffer = function (type) {
  16261. var gl = this._gl;
  16262. //clear existing errors
  16263. while (gl.getError() !== gl.NO_ERROR) { }
  16264. var successful = true;
  16265. var texture = gl.createTexture();
  16266. gl.bindTexture(gl.TEXTURE_2D, texture);
  16267. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16268. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16269. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16270. var fb = gl.createFramebuffer();
  16271. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16272. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16273. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16274. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16275. successful = successful && (gl.getError() === gl.NO_ERROR);
  16276. //try render by clearing frame buffer's color buffer
  16277. if (successful) {
  16278. gl.clear(gl.COLOR_BUFFER_BIT);
  16279. successful = successful && (gl.getError() === gl.NO_ERROR);
  16280. }
  16281. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16282. if (successful) {
  16283. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16284. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16285. var readFormat = gl.RGBA;
  16286. var readType = gl.UNSIGNED_BYTE;
  16287. var buffer = new Uint8Array(4);
  16288. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16289. successful = successful && (gl.getError() === gl.NO_ERROR);
  16290. }
  16291. //clean up
  16292. gl.deleteTexture(texture);
  16293. gl.deleteFramebuffer(fb);
  16294. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16295. //clear accumulated errors
  16296. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16297. return successful;
  16298. };
  16299. /** @ignore */
  16300. Engine.prototype._getWebGLTextureType = function (type) {
  16301. if (type === Engine.TEXTURETYPE_FLOAT) {
  16302. return this._gl.FLOAT;
  16303. }
  16304. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16305. // Add Half Float Constant.
  16306. return this._gl.HALF_FLOAT_OES;
  16307. }
  16308. return this._gl.UNSIGNED_BYTE;
  16309. };
  16310. ;
  16311. Engine.prototype._getInternalFormat = function (format) {
  16312. var internalFormat = this._gl.RGBA;
  16313. switch (format) {
  16314. case Engine.TEXTUREFORMAT_ALPHA:
  16315. internalFormat = this._gl.ALPHA;
  16316. break;
  16317. case Engine.TEXTUREFORMAT_LUMINANCE:
  16318. internalFormat = this._gl.LUMINANCE;
  16319. break;
  16320. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  16321. internalFormat = this._gl.LUMINANCE_ALPHA;
  16322. break;
  16323. case Engine.TEXTUREFORMAT_RGB:
  16324. case Engine.TEXTUREFORMAT_RGB32F:
  16325. internalFormat = this._gl.RGB;
  16326. break;
  16327. case Engine.TEXTUREFORMAT_RGBA:
  16328. case Engine.TEXTUREFORMAT_RGBA32F:
  16329. internalFormat = this._gl.RGBA;
  16330. break;
  16331. case Engine.TEXTUREFORMAT_R32F:
  16332. internalFormat = this._gl.RED;
  16333. break;
  16334. case Engine.TEXTUREFORMAT_RG32F:
  16335. internalFormat = this._gl.RG;
  16336. break;
  16337. }
  16338. return internalFormat;
  16339. };
  16340. /** @ignore */
  16341. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  16342. if (this._webGLVersion === 1) {
  16343. if (format) {
  16344. switch (format) {
  16345. case Engine.TEXTUREFORMAT_LUMINANCE:
  16346. return this._gl.LUMINANCE;
  16347. }
  16348. }
  16349. return this._gl.RGBA;
  16350. }
  16351. if (type === Engine.TEXTURETYPE_FLOAT) {
  16352. if (format) {
  16353. switch (format) {
  16354. case Engine.TEXTUREFORMAT_R32F:
  16355. return this._gl.R32F;
  16356. case Engine.TEXTUREFORMAT_RG32F:
  16357. return this._gl.RG32F;
  16358. case Engine.TEXTUREFORMAT_RGB32F:
  16359. return this._gl.RGB32F;
  16360. }
  16361. }
  16362. return this._gl.RGBA32F;
  16363. }
  16364. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16365. return this._gl.RGBA16F;
  16366. }
  16367. if (format) {
  16368. switch (format) {
  16369. case Engine.TEXTUREFORMAT_LUMINANCE:
  16370. return this._gl.LUMINANCE;
  16371. }
  16372. }
  16373. return this._gl.RGBA;
  16374. };
  16375. ;
  16376. /** @ignore */
  16377. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  16378. if (type === Engine.TEXTURETYPE_FLOAT) {
  16379. return this._gl.RGBA32F;
  16380. }
  16381. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16382. return this._gl.RGBA16F;
  16383. }
  16384. return this._gl.RGBA8;
  16385. };
  16386. ;
  16387. /**
  16388. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  16389. * @return the new query
  16390. */
  16391. Engine.prototype.createQuery = function () {
  16392. return this._gl.createQuery();
  16393. };
  16394. /**
  16395. * Delete and release a webGL query
  16396. * @param query defines the query to delete
  16397. * @return the current engine
  16398. */
  16399. Engine.prototype.deleteQuery = function (query) {
  16400. this._gl.deleteQuery(query);
  16401. return this;
  16402. };
  16403. /**
  16404. * Check if a given query has resolved and got its value
  16405. * @param query defines the query to check
  16406. * @returns true if the query got its value
  16407. */
  16408. Engine.prototype.isQueryResultAvailable = function (query) {
  16409. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  16410. };
  16411. /**
  16412. * Gets the value of a given query
  16413. * @param query defines the query to check
  16414. * @returns the value of the query
  16415. */
  16416. Engine.prototype.getQueryResult = function (query) {
  16417. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  16418. };
  16419. /**
  16420. * Initiates an occlusion query
  16421. * @param algorithmType defines the algorithm to use
  16422. * @param query defines the query to use
  16423. * @returns the current engine
  16424. * @see http://doc.babylonjs.com/features/occlusionquery
  16425. */
  16426. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  16427. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  16428. this._gl.beginQuery(glAlgorithm, query);
  16429. return this;
  16430. };
  16431. /**
  16432. * Ends an occlusion query
  16433. * @see http://doc.babylonjs.com/features/occlusionquery
  16434. * @param algorithmType defines the algorithm to use
  16435. * @returns the current engine
  16436. */
  16437. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  16438. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  16439. this._gl.endQuery(glAlgorithm);
  16440. return this;
  16441. };
  16442. /* Time queries */
  16443. Engine.prototype._createTimeQuery = function () {
  16444. var timerQuery = this._caps.timerQuery;
  16445. if (timerQuery.createQueryEXT) {
  16446. return timerQuery.createQueryEXT();
  16447. }
  16448. return this.createQuery();
  16449. };
  16450. Engine.prototype._deleteTimeQuery = function (query) {
  16451. var timerQuery = this._caps.timerQuery;
  16452. if (timerQuery.deleteQueryEXT) {
  16453. timerQuery.deleteQueryEXT(query);
  16454. return;
  16455. }
  16456. this.deleteQuery(query);
  16457. };
  16458. Engine.prototype._getTimeQueryResult = function (query) {
  16459. var timerQuery = this._caps.timerQuery;
  16460. if (timerQuery.getQueryObjectEXT) {
  16461. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  16462. }
  16463. return this.getQueryResult(query);
  16464. };
  16465. Engine.prototype._getTimeQueryAvailability = function (query) {
  16466. var timerQuery = this._caps.timerQuery;
  16467. if (timerQuery.getQueryObjectEXT) {
  16468. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  16469. }
  16470. return this.isQueryResultAvailable(query);
  16471. };
  16472. /**
  16473. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  16474. * Please note that only one query can be issued at a time
  16475. * @returns a time token used to track the time span
  16476. */
  16477. Engine.prototype.startTimeQuery = function () {
  16478. var timerQuery = this._caps.timerQuery;
  16479. if (!timerQuery) {
  16480. return null;
  16481. }
  16482. var token = new BABYLON._TimeToken();
  16483. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  16484. if (this._caps.canUseTimestampForTimerQuery) {
  16485. token._startTimeQuery = this._createTimeQuery();
  16486. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  16487. }
  16488. else {
  16489. if (this._currentNonTimestampToken) {
  16490. return this._currentNonTimestampToken;
  16491. }
  16492. token._timeElapsedQuery = this._createTimeQuery();
  16493. if (timerQuery.beginQueryEXT) {
  16494. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  16495. }
  16496. else {
  16497. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  16498. }
  16499. this._currentNonTimestampToken = token;
  16500. }
  16501. return token;
  16502. };
  16503. /**
  16504. * Ends a time query
  16505. * @param token defines the token used to measure the time span
  16506. * @returns the time spent (in ns)
  16507. */
  16508. Engine.prototype.endTimeQuery = function (token) {
  16509. var timerQuery = this._caps.timerQuery;
  16510. if (!timerQuery || !token) {
  16511. return -1;
  16512. }
  16513. if (this._caps.canUseTimestampForTimerQuery) {
  16514. if (!token._startTimeQuery) {
  16515. return -1;
  16516. }
  16517. if (!token._endTimeQuery) {
  16518. token._endTimeQuery = this._createTimeQuery();
  16519. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  16520. }
  16521. }
  16522. else if (!token._timeElapsedQueryEnded) {
  16523. if (!token._timeElapsedQuery) {
  16524. return -1;
  16525. }
  16526. if (timerQuery.endQueryEXT) {
  16527. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  16528. }
  16529. else {
  16530. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  16531. }
  16532. token._timeElapsedQueryEnded = true;
  16533. }
  16534. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  16535. var available = false;
  16536. if (token._endTimeQuery) {
  16537. available = this._getTimeQueryAvailability(token._endTimeQuery);
  16538. }
  16539. else if (token._timeElapsedQuery) {
  16540. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  16541. }
  16542. if (available && !disjoint) {
  16543. var result = 0;
  16544. if (this._caps.canUseTimestampForTimerQuery) {
  16545. if (!token._startTimeQuery || !token._endTimeQuery) {
  16546. return -1;
  16547. }
  16548. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  16549. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  16550. result = timeEnd - timeStart;
  16551. this._deleteTimeQuery(token._startTimeQuery);
  16552. this._deleteTimeQuery(token._endTimeQuery);
  16553. token._startTimeQuery = null;
  16554. token._endTimeQuery = null;
  16555. }
  16556. else {
  16557. if (!token._timeElapsedQuery) {
  16558. return -1;
  16559. }
  16560. result = this._getTimeQueryResult(token._timeElapsedQuery);
  16561. this._deleteTimeQuery(token._timeElapsedQuery);
  16562. token._timeElapsedQuery = null;
  16563. token._timeElapsedQueryEnded = false;
  16564. this._currentNonTimestampToken = null;
  16565. }
  16566. return result;
  16567. }
  16568. return -1;
  16569. };
  16570. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  16571. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  16572. };
  16573. // Transform feedback
  16574. /**
  16575. * Creates a webGL transform feedback object
  16576. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  16577. * @returns the webGL transform feedback object
  16578. */
  16579. Engine.prototype.createTransformFeedback = function () {
  16580. return this._gl.createTransformFeedback();
  16581. };
  16582. /**
  16583. * Delete a webGL transform feedback object
  16584. * @param value defines the webGL transform feedback object to delete
  16585. */
  16586. Engine.prototype.deleteTransformFeedback = function (value) {
  16587. this._gl.deleteTransformFeedback(value);
  16588. };
  16589. /**
  16590. * Bind a webGL transform feedback object to the webgl context
  16591. * @param value defines the webGL transform feedback object to bind
  16592. */
  16593. Engine.prototype.bindTransformFeedback = function (value) {
  16594. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  16595. };
  16596. /**
  16597. * Begins a transform feedback operation
  16598. * @param usePoints defines if points or triangles must be used
  16599. */
  16600. Engine.prototype.beginTransformFeedback = function (usePoints) {
  16601. if (usePoints === void 0) { usePoints = true; }
  16602. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  16603. };
  16604. /**
  16605. * Ends a transform feedback operation
  16606. */
  16607. Engine.prototype.endTransformFeedback = function () {
  16608. this._gl.endTransformFeedback();
  16609. };
  16610. /**
  16611. * Specify the varyings to use with transform feedback
  16612. * @param program defines the associated webGL program
  16613. * @param value defines the list of strings representing the varying names
  16614. */
  16615. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  16616. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  16617. };
  16618. /**
  16619. * Bind a webGL buffer for a transform feedback operation
  16620. * @param value defines the webGL buffer to bind
  16621. */
  16622. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  16623. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  16624. };
  16625. /** @ignore */
  16626. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  16627. var _this = this;
  16628. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  16629. this._activeRequests.push(request);
  16630. request.onCompleteObservable.add(function (request) {
  16631. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  16632. });
  16633. return request;
  16634. };
  16635. /** @ignore */
  16636. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  16637. var _this = this;
  16638. return new Promise(function (resolve, reject) {
  16639. _this._loadFile(url, function (data) {
  16640. resolve(data);
  16641. }, undefined, database, useArrayBuffer, function (request, exception) {
  16642. reject(exception);
  16643. });
  16644. });
  16645. };
  16646. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  16647. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  16648. var onload = function (data) {
  16649. loadedFiles[index] = data;
  16650. loadedFiles._internalCount++;
  16651. if (loadedFiles._internalCount === 6) {
  16652. onfinish(loadedFiles);
  16653. }
  16654. };
  16655. var onerror = function (request, exception) {
  16656. if (onErrorCallBack && request) {
  16657. onErrorCallBack(request.status + " " + request.statusText, exception);
  16658. }
  16659. };
  16660. this._loadFile(url, onload, undefined, undefined, true, onerror);
  16661. };
  16662. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  16663. if (onError === void 0) { onError = null; }
  16664. var loadedFiles = [];
  16665. loadedFiles._internalCount = 0;
  16666. for (var index = 0; index < 6; index++) {
  16667. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  16668. }
  16669. };
  16670. // Statics
  16671. /**
  16672. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  16673. * @returns true if the engine can be created
  16674. * @ignoreNaming
  16675. */
  16676. Engine.isSupported = function () {
  16677. try {
  16678. var tempcanvas = document.createElement("canvas");
  16679. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  16680. return gl != null && !!window.WebGLRenderingContext;
  16681. }
  16682. catch (e) {
  16683. return false;
  16684. }
  16685. };
  16686. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  16687. Engine.ExceptionList = [
  16688. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  16689. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  16690. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  16691. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  16692. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  16693. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  16694. ];
  16695. /** Gets the list of created engines */
  16696. Engine.Instances = new Array();
  16697. // Const statics
  16698. Engine._ALPHA_DISABLE = 0;
  16699. Engine._ALPHA_ADD = 1;
  16700. Engine._ALPHA_COMBINE = 2;
  16701. Engine._ALPHA_SUBTRACT = 3;
  16702. Engine._ALPHA_MULTIPLY = 4;
  16703. Engine._ALPHA_MAXIMIZED = 5;
  16704. Engine._ALPHA_ONEONE = 6;
  16705. Engine._ALPHA_PREMULTIPLIED = 7;
  16706. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  16707. Engine._ALPHA_INTERPOLATE = 9;
  16708. Engine._ALPHA_SCREENMODE = 10;
  16709. Engine._DELAYLOADSTATE_NONE = 0;
  16710. Engine._DELAYLOADSTATE_LOADED = 1;
  16711. Engine._DELAYLOADSTATE_LOADING = 2;
  16712. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  16713. Engine._TEXTUREFORMAT_ALPHA = 0;
  16714. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  16715. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  16716. Engine._TEXTUREFORMAT_RGB = 4;
  16717. Engine._TEXTUREFORMAT_RGBA = 5;
  16718. Engine._TEXTUREFORMAT_R32F = 6;
  16719. Engine._TEXTUREFORMAT_RG32F = 7;
  16720. Engine._TEXTUREFORMAT_RGB32F = 8;
  16721. Engine._TEXTUREFORMAT_RGBA32F = 9;
  16722. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  16723. Engine._TEXTURETYPE_FLOAT = 1;
  16724. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  16725. // Depht or Stencil test Constants.
  16726. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  16727. 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.
  16728. 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.
  16729. 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.
  16730. 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.
  16731. 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.
  16732. 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.
  16733. 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.
  16734. // Stencil Actions Constants.
  16735. Engine._KEEP = 0x1E00;
  16736. Engine._REPLACE = 0x1E01;
  16737. Engine._INCR = 0x1E02;
  16738. Engine._DECR = 0x1E03;
  16739. Engine._INVERT = 0x150A;
  16740. Engine._INCR_WRAP = 0x8507;
  16741. Engine._DECR_WRAP = 0x8508;
  16742. // Texture rescaling mode
  16743. Engine._SCALEMODE_FLOOR = 1;
  16744. Engine._SCALEMODE_NEAREST = 2;
  16745. Engine._SCALEMODE_CEILING = 3;
  16746. // Updatable statics so stick with vars here
  16747. /**
  16748. * Gets or sets the epsilon value used by collision engine
  16749. */
  16750. Engine.CollisionsEpsilon = 0.001;
  16751. /**
  16752. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  16753. */
  16754. Engine.CodeRepository = "src/";
  16755. /**
  16756. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  16757. */
  16758. Engine.ShadersRepository = "src/Shaders/";
  16759. return Engine;
  16760. }());
  16761. BABYLON.Engine = Engine;
  16762. })(BABYLON || (BABYLON = {}));
  16763. //# sourceMappingURL=babylon.engine.js.map
  16764. "use strict";
  16765. var BABYLON;
  16766. (function (BABYLON) {
  16767. /**
  16768. * Node is the basic class for all scene objects (Mesh, Light Camera).
  16769. */
  16770. var Node = /** @class */ (function () {
  16771. /**
  16772. * Creates a new Node
  16773. * @param {string} name - the name and id to be given to this node
  16774. * @param {BABYLON.Scene} the scene this node will be added to
  16775. */
  16776. function Node(name, scene) {
  16777. if (scene === void 0) { scene = null; }
  16778. /**
  16779. * Gets or sets a string used to store user defined state for the node
  16780. */
  16781. this.state = "";
  16782. /**
  16783. * Gets or sets an object used to store user defined information for the node
  16784. */
  16785. this.metadata = null;
  16786. /**
  16787. * Gets or sets a boolean used to define if the node must be serialized
  16788. */
  16789. this.doNotSerialize = false;
  16790. /** @ignore */
  16791. this._isDisposed = false;
  16792. /**
  16793. * Gets a list of Animations associated with the node
  16794. */
  16795. this.animations = new Array();
  16796. this._ranges = {};
  16797. this._isEnabled = true;
  16798. this._isReady = true;
  16799. /** @ignore */
  16800. this._currentRenderId = -1;
  16801. this._parentRenderId = -1;
  16802. this._childRenderId = -1;
  16803. this._animationPropertiesOverride = null;
  16804. /**
  16805. * An event triggered when the mesh is disposed
  16806. */
  16807. this.onDisposeObservable = new BABYLON.Observable();
  16808. // Behaviors
  16809. this._behaviors = new Array();
  16810. this.name = name;
  16811. this.id = name;
  16812. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  16813. this.uniqueId = this._scene.getUniqueId();
  16814. this._initCache();
  16815. }
  16816. /**
  16817. * Gets a boolean indicating if the node has been disposed
  16818. * @returns true if the node was disposed
  16819. */
  16820. Node.prototype.isDisposed = function () {
  16821. return this._isDisposed;
  16822. };
  16823. Object.defineProperty(Node.prototype, "parent", {
  16824. get: function () {
  16825. return this._parentNode;
  16826. },
  16827. /**
  16828. * Gets or sets the parent of the node
  16829. */
  16830. set: function (parent) {
  16831. if (this._parentNode === parent) {
  16832. return;
  16833. }
  16834. // Remove self from list of children of parent
  16835. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  16836. var index = this._parentNode._children.indexOf(this);
  16837. if (index !== -1) {
  16838. this._parentNode._children.splice(index, 1);
  16839. }
  16840. }
  16841. // Store new parent
  16842. this._parentNode = parent;
  16843. // Add as child to new parent
  16844. if (this._parentNode) {
  16845. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  16846. this._parentNode._children = new Array();
  16847. }
  16848. this._parentNode._children.push(this);
  16849. }
  16850. },
  16851. enumerable: true,
  16852. configurable: true
  16853. });
  16854. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  16855. /**
  16856. * Gets or sets the animation properties override
  16857. */
  16858. get: function () {
  16859. return this._animationPropertiesOverride;
  16860. },
  16861. set: function (value) {
  16862. this._animationPropertiesOverride = value;
  16863. },
  16864. enumerable: true,
  16865. configurable: true
  16866. });
  16867. /**
  16868. * Gets a string idenfifying the name of the class
  16869. * @returns "Node" string
  16870. */
  16871. Node.prototype.getClassName = function () {
  16872. return "Node";
  16873. };
  16874. Object.defineProperty(Node.prototype, "onDispose", {
  16875. /**
  16876. * Sets a callback that will be raised when the node will be disposed
  16877. */
  16878. set: function (callback) {
  16879. if (this._onDisposeObserver) {
  16880. this.onDisposeObservable.remove(this._onDisposeObserver);
  16881. }
  16882. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  16883. },
  16884. enumerable: true,
  16885. configurable: true
  16886. });
  16887. /**
  16888. * Gets the scene of the node
  16889. * @returns a {BABYLON.Scene}
  16890. */
  16891. Node.prototype.getScene = function () {
  16892. return this._scene;
  16893. };
  16894. /**
  16895. * Gets the engine of the node
  16896. * @returns a {BABYLON.Engine}
  16897. */
  16898. Node.prototype.getEngine = function () {
  16899. return this._scene.getEngine();
  16900. };
  16901. /**
  16902. * Attach a behavior to the node
  16903. * @see http://doc.babylonjs.com/features/behaviour
  16904. * @param behavior defines the behavior to attach
  16905. * @returns the current Node
  16906. */
  16907. Node.prototype.addBehavior = function (behavior) {
  16908. var _this = this;
  16909. var index = this._behaviors.indexOf(behavior);
  16910. if (index !== -1) {
  16911. return this;
  16912. }
  16913. behavior.init();
  16914. if (this._scene.isLoading) {
  16915. // We defer the attach when the scene will be loaded
  16916. var observer = this._scene.onDataLoadedObservable.add(function () {
  16917. behavior.attach(_this);
  16918. setTimeout(function () {
  16919. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  16920. _this._scene.onDataLoadedObservable.remove(observer);
  16921. }, 0);
  16922. });
  16923. }
  16924. else {
  16925. behavior.attach(this);
  16926. }
  16927. this._behaviors.push(behavior);
  16928. return this;
  16929. };
  16930. /**
  16931. * Remove an attached behavior
  16932. * @see http://doc.babylonjs.com/features/behaviour
  16933. * @param behavior defines the behavior to attach
  16934. * @returns the current Node
  16935. */
  16936. Node.prototype.removeBehavior = function (behavior) {
  16937. var index = this._behaviors.indexOf(behavior);
  16938. if (index === -1) {
  16939. return this;
  16940. }
  16941. this._behaviors[index].detach();
  16942. this._behaviors.splice(index, 1);
  16943. return this;
  16944. };
  16945. Object.defineProperty(Node.prototype, "behaviors", {
  16946. /**
  16947. * Gets the list of attached behaviors
  16948. * @see http://doc.babylonjs.com/features/behaviour
  16949. */
  16950. get: function () {
  16951. return this._behaviors;
  16952. },
  16953. enumerable: true,
  16954. configurable: true
  16955. });
  16956. /**
  16957. * Gets an attached behavior by name
  16958. * @param name defines the name of the behavior to look for
  16959. * @see http://doc.babylonjs.com/features/behaviour
  16960. * @returns null if behavior was not found else the requested behavior
  16961. */
  16962. Node.prototype.getBehaviorByName = function (name) {
  16963. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  16964. var behavior = _a[_i];
  16965. if (behavior.name === name) {
  16966. return behavior;
  16967. }
  16968. }
  16969. return null;
  16970. };
  16971. /**
  16972. * Returns the world matrix of the node
  16973. * @returns a matrix containing the node's world matrix
  16974. */
  16975. Node.prototype.getWorldMatrix = function () {
  16976. return BABYLON.Matrix.Identity();
  16977. };
  16978. // override it in derived class if you add new variables to the cache
  16979. // and call the parent class method
  16980. /** @ignore */
  16981. Node.prototype._initCache = function () {
  16982. this._cache = {};
  16983. this._cache.parent = undefined;
  16984. };
  16985. /** @ignore */
  16986. Node.prototype.updateCache = function (force) {
  16987. if (!force && this.isSynchronized())
  16988. return;
  16989. this._cache.parent = this.parent;
  16990. this._updateCache();
  16991. };
  16992. // override it in derived class if you add new variables to the cache
  16993. // and call the parent class method if !ignoreParentClass
  16994. /** @ignore */
  16995. Node.prototype._updateCache = function (ignoreParentClass) {
  16996. };
  16997. // override it in derived class if you add new variables to the cache
  16998. /** @ignore */
  16999. Node.prototype._isSynchronized = function () {
  17000. return true;
  17001. };
  17002. /** @ignore */
  17003. Node.prototype._markSyncedWithParent = function () {
  17004. if (this.parent) {
  17005. this._parentRenderId = this.parent._childRenderId;
  17006. }
  17007. };
  17008. /** @ignore */
  17009. Node.prototype.isSynchronizedWithParent = function () {
  17010. if (!this.parent) {
  17011. return true;
  17012. }
  17013. if (this._parentRenderId !== this.parent._childRenderId) {
  17014. return false;
  17015. }
  17016. return this.parent.isSynchronized();
  17017. };
  17018. /** @ignore */
  17019. Node.prototype.isSynchronized = function (updateCache) {
  17020. var check = this.hasNewParent();
  17021. check = check || !this.isSynchronizedWithParent();
  17022. check = check || !this._isSynchronized();
  17023. if (updateCache)
  17024. this.updateCache(true);
  17025. return !check;
  17026. };
  17027. /** @ignore */
  17028. Node.prototype.hasNewParent = function (update) {
  17029. if (this._cache.parent === this.parent)
  17030. return false;
  17031. if (update)
  17032. this._cache.parent = this.parent;
  17033. return true;
  17034. };
  17035. /**
  17036. * Is this node ready to be used/rendered
  17037. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17038. * @return true if the node is ready
  17039. */
  17040. Node.prototype.isReady = function (completeCheck) {
  17041. if (completeCheck === void 0) { completeCheck = false; }
  17042. return this._isReady;
  17043. };
  17044. /**
  17045. * Is this node enabled?
  17046. * 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
  17047. * @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
  17048. * @return whether this node (and its parent) is enabled
  17049. */
  17050. Node.prototype.isEnabled = function (checkAncestors) {
  17051. if (checkAncestors === void 0) { checkAncestors = true; }
  17052. if (checkAncestors === false) {
  17053. return this._isEnabled;
  17054. }
  17055. if (this._isEnabled === false) {
  17056. return false;
  17057. }
  17058. if (this.parent !== undefined && this.parent !== null) {
  17059. return this.parent.isEnabled(checkAncestors);
  17060. }
  17061. return true;
  17062. };
  17063. /**
  17064. * Set the enabled state of this node
  17065. * @param value defines the new enabled state
  17066. */
  17067. Node.prototype.setEnabled = function (value) {
  17068. this._isEnabled = value;
  17069. };
  17070. /**
  17071. * Is this node a descendant of the given node?
  17072. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17073. * @param ancestor defines the parent node to inspect
  17074. * @returns a boolean indicating if this node is a descendant of the given node
  17075. */
  17076. Node.prototype.isDescendantOf = function (ancestor) {
  17077. if (this.parent) {
  17078. if (this.parent === ancestor) {
  17079. return true;
  17080. }
  17081. return this.parent.isDescendantOf(ancestor);
  17082. }
  17083. return false;
  17084. };
  17085. /** @ignore */
  17086. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17087. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17088. if (!this._children) {
  17089. return;
  17090. }
  17091. for (var index = 0; index < this._children.length; index++) {
  17092. var item = this._children[index];
  17093. if (!predicate || predicate(item)) {
  17094. results.push(item);
  17095. }
  17096. if (!directDescendantsOnly) {
  17097. item._getDescendants(results, false, predicate);
  17098. }
  17099. }
  17100. };
  17101. /**
  17102. * Will return all nodes that have this node as ascendant
  17103. * @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
  17104. * @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
  17105. * @return all children nodes of all types
  17106. */
  17107. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17108. var results = new Array();
  17109. this._getDescendants(results, directDescendantsOnly, predicate);
  17110. return results;
  17111. };
  17112. /**
  17113. * Get all child-meshes of this node
  17114. * @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
  17115. * @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
  17116. * @returns an array of {BABYLON.AbstractMesh}
  17117. */
  17118. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17119. var results = [];
  17120. this._getDescendants(results, directDescendantsOnly, function (node) {
  17121. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17122. });
  17123. return results;
  17124. };
  17125. /**
  17126. * Get all child-transformNodes of this node
  17127. * @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
  17128. * @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
  17129. * @returns an array of {BABYLON.TransformNode}
  17130. */
  17131. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17132. var results = [];
  17133. this._getDescendants(results, directDescendantsOnly, function (node) {
  17134. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17135. });
  17136. return results;
  17137. };
  17138. /**
  17139. * Get all direct children of this node
  17140. * @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
  17141. * @returns an array of {BABYLON.Node}
  17142. */
  17143. Node.prototype.getChildren = function (predicate) {
  17144. return this.getDescendants(true, predicate);
  17145. };
  17146. /** @ignore */
  17147. Node.prototype._setReady = function (state) {
  17148. if (state === this._isReady) {
  17149. return;
  17150. }
  17151. if (!state) {
  17152. this._isReady = false;
  17153. return;
  17154. }
  17155. if (this.onReady) {
  17156. this.onReady(this);
  17157. }
  17158. this._isReady = true;
  17159. };
  17160. /**
  17161. * Get an animation by name
  17162. * @param name defines the name of the animation to look for
  17163. * @returns null if not found else the requested animation
  17164. */
  17165. Node.prototype.getAnimationByName = function (name) {
  17166. for (var i = 0; i < this.animations.length; i++) {
  17167. var animation = this.animations[i];
  17168. if (animation.name === name) {
  17169. return animation;
  17170. }
  17171. }
  17172. return null;
  17173. };
  17174. /**
  17175. * Creates an animation range for this node
  17176. * @param name defines the name of the range
  17177. * @param from defines the starting key
  17178. * @param to defines the end key
  17179. */
  17180. Node.prototype.createAnimationRange = function (name, from, to) {
  17181. // check name not already in use
  17182. if (!this._ranges[name]) {
  17183. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17184. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17185. if (this.animations[i]) {
  17186. this.animations[i].createRange(name, from, to);
  17187. }
  17188. }
  17189. }
  17190. };
  17191. /**
  17192. * Delete a specific animation range
  17193. * @param name defines the name of the range to delete
  17194. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17195. */
  17196. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17197. if (deleteFrames === void 0) { deleteFrames = true; }
  17198. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17199. if (this.animations[i]) {
  17200. this.animations[i].deleteRange(name, deleteFrames);
  17201. }
  17202. }
  17203. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17204. };
  17205. /**
  17206. * Get an animation range by name
  17207. * @param name defines the name of the animation range to look for
  17208. * @returns null if not found else the requested animation range
  17209. */
  17210. Node.prototype.getAnimationRange = function (name) {
  17211. return this._ranges[name];
  17212. };
  17213. /**
  17214. * Will start the animation sequence
  17215. * @param name defines the range frames for animation sequence
  17216. * @param loop defines if the animation should loop (false by default)
  17217. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17218. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17219. * @returns the object created for this animation. If range does not exist, it will return null
  17220. */
  17221. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17222. var range = this.getAnimationRange(name);
  17223. if (!range) {
  17224. return null;
  17225. }
  17226. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17227. };
  17228. /**
  17229. * Serialize animation ranges into a JSON compatible object
  17230. * @returns serialization object
  17231. */
  17232. Node.prototype.serializeAnimationRanges = function () {
  17233. var serializationRanges = [];
  17234. for (var name in this._ranges) {
  17235. var localRange = this._ranges[name];
  17236. if (!localRange) {
  17237. continue;
  17238. }
  17239. var range = {};
  17240. range.name = name;
  17241. range.from = localRange.from;
  17242. range.to = localRange.to;
  17243. serializationRanges.push(range);
  17244. }
  17245. return serializationRanges;
  17246. };
  17247. /**
  17248. * Computes the world matrix of the node
  17249. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17250. * @returns the world matrix
  17251. */
  17252. Node.prototype.computeWorldMatrix = function (force) {
  17253. return BABYLON.Matrix.Identity();
  17254. };
  17255. /**
  17256. * Releases resources associated with this node.
  17257. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17258. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17259. */
  17260. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17261. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17262. if (!doNotRecurse) {
  17263. var nodes = this.getDescendants(true);
  17264. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17265. var node = nodes_1[_i];
  17266. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17267. }
  17268. }
  17269. else {
  17270. var transformNodes = this.getChildTransformNodes(true);
  17271. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17272. var transformNode = transformNodes_1[_a];
  17273. transformNode.parent = null;
  17274. transformNode.computeWorldMatrix(true);
  17275. }
  17276. }
  17277. this.parent = null;
  17278. // Callback
  17279. this.onDisposeObservable.notifyObservers(this);
  17280. this.onDisposeObservable.clear();
  17281. // Behaviors
  17282. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  17283. var behavior = _c[_b];
  17284. behavior.detach();
  17285. }
  17286. this._behaviors = [];
  17287. this._isDisposed = true;
  17288. };
  17289. /**
  17290. * Parse animation range data from a serialization object and store them into a given node
  17291. * @param node defines where to store the animation ranges
  17292. * @param parsedNode defines the serialization object to read data from
  17293. * @param scene defines the hosting scene
  17294. */
  17295. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  17296. if (parsedNode.ranges) {
  17297. for (var index = 0; index < parsedNode.ranges.length; index++) {
  17298. var data = parsedNode.ranges[index];
  17299. node.createAnimationRange(data.name, data.from, data.to);
  17300. }
  17301. }
  17302. };
  17303. __decorate([
  17304. BABYLON.serialize()
  17305. ], Node.prototype, "name", void 0);
  17306. __decorate([
  17307. BABYLON.serialize()
  17308. ], Node.prototype, "id", void 0);
  17309. __decorate([
  17310. BABYLON.serialize()
  17311. ], Node.prototype, "uniqueId", void 0);
  17312. __decorate([
  17313. BABYLON.serialize()
  17314. ], Node.prototype, "state", void 0);
  17315. __decorate([
  17316. BABYLON.serialize()
  17317. ], Node.prototype, "metadata", void 0);
  17318. return Node;
  17319. }());
  17320. BABYLON.Node = Node;
  17321. })(BABYLON || (BABYLON = {}));
  17322. //# sourceMappingURL=babylon.node.js.map
  17323. "use strict";
  17324. var BABYLON;
  17325. (function (BABYLON) {
  17326. var BoundingSphere = /** @class */ (function () {
  17327. function BoundingSphere(minimum, maximum) {
  17328. this.minimum = minimum;
  17329. this.maximum = maximum;
  17330. this._tempRadiusVector = BABYLON.Vector3.Zero();
  17331. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  17332. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  17333. this.radius = distance * 0.5;
  17334. this.centerWorld = BABYLON.Vector3.Zero();
  17335. this._update(BABYLON.Matrix.Identity());
  17336. }
  17337. // Methods
  17338. BoundingSphere.prototype._update = function (world) {
  17339. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  17340. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  17341. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  17342. };
  17343. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  17344. for (var i = 0; i < 6; i++) {
  17345. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  17346. return false;
  17347. }
  17348. return true;
  17349. };
  17350. BoundingSphere.prototype.intersectsPoint = function (point) {
  17351. var x = this.centerWorld.x - point.x;
  17352. var y = this.centerWorld.y - point.y;
  17353. var z = this.centerWorld.z - point.z;
  17354. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17355. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  17356. return false;
  17357. return true;
  17358. };
  17359. // Statics
  17360. BoundingSphere.Intersects = function (sphere0, sphere1) {
  17361. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  17362. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  17363. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  17364. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17365. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  17366. return false;
  17367. return true;
  17368. };
  17369. return BoundingSphere;
  17370. }());
  17371. BABYLON.BoundingSphere = BoundingSphere;
  17372. })(BABYLON || (BABYLON = {}));
  17373. //# sourceMappingURL=babylon.boundingSphere.js.map
  17374. "use strict";
  17375. var BABYLON;
  17376. (function (BABYLON) {
  17377. var BoundingBox = /** @class */ (function () {
  17378. function BoundingBox(minimum, maximum) {
  17379. this.minimum = minimum;
  17380. this.maximum = maximum;
  17381. this.vectors = new Array();
  17382. this.vectorsWorld = new Array();
  17383. // Bounding vectors
  17384. this.vectors.push(this.minimum.clone());
  17385. this.vectors.push(this.maximum.clone());
  17386. this.vectors.push(this.minimum.clone());
  17387. this.vectors[2].x = this.maximum.x;
  17388. this.vectors.push(this.minimum.clone());
  17389. this.vectors[3].y = this.maximum.y;
  17390. this.vectors.push(this.minimum.clone());
  17391. this.vectors[4].z = this.maximum.z;
  17392. this.vectors.push(this.maximum.clone());
  17393. this.vectors[5].z = this.minimum.z;
  17394. this.vectors.push(this.maximum.clone());
  17395. this.vectors[6].x = this.minimum.x;
  17396. this.vectors.push(this.maximum.clone());
  17397. this.vectors[7].y = this.minimum.y;
  17398. // OBB
  17399. this.center = this.maximum.add(this.minimum).scale(0.5);
  17400. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  17401. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  17402. // World
  17403. for (var index = 0; index < this.vectors.length; index++) {
  17404. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  17405. }
  17406. this.minimumWorld = BABYLON.Vector3.Zero();
  17407. this.maximumWorld = BABYLON.Vector3.Zero();
  17408. this.centerWorld = BABYLON.Vector3.Zero();
  17409. this.extendSizeWorld = BABYLON.Vector3.Zero();
  17410. this._update(BABYLON.Matrix.Identity());
  17411. }
  17412. // Methods
  17413. BoundingBox.prototype.getWorldMatrix = function () {
  17414. return this._worldMatrix;
  17415. };
  17416. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  17417. this._worldMatrix.copyFrom(matrix);
  17418. return this;
  17419. };
  17420. BoundingBox.prototype._update = function (world) {
  17421. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  17422. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  17423. for (var index = 0; index < this.vectors.length; index++) {
  17424. var v = this.vectorsWorld[index];
  17425. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  17426. if (v.x < this.minimumWorld.x)
  17427. this.minimumWorld.x = v.x;
  17428. if (v.y < this.minimumWorld.y)
  17429. this.minimumWorld.y = v.y;
  17430. if (v.z < this.minimumWorld.z)
  17431. this.minimumWorld.z = v.z;
  17432. if (v.x > this.maximumWorld.x)
  17433. this.maximumWorld.x = v.x;
  17434. if (v.y > this.maximumWorld.y)
  17435. this.maximumWorld.y = v.y;
  17436. if (v.z > this.maximumWorld.z)
  17437. this.maximumWorld.z = v.z;
  17438. }
  17439. // Extend
  17440. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  17441. this.extendSizeWorld.scaleInPlace(0.5);
  17442. // OBB
  17443. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  17444. this.centerWorld.scaleInPlace(0.5);
  17445. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  17446. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  17447. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  17448. this._worldMatrix = world;
  17449. };
  17450. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  17451. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  17452. };
  17453. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  17454. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  17455. };
  17456. BoundingBox.prototype.intersectsPoint = function (point) {
  17457. var delta = -BABYLON.Epsilon;
  17458. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  17459. return false;
  17460. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  17461. return false;
  17462. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  17463. return false;
  17464. return true;
  17465. };
  17466. BoundingBox.prototype.intersectsSphere = function (sphere) {
  17467. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  17468. };
  17469. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  17470. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  17471. return false;
  17472. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  17473. return false;
  17474. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  17475. return false;
  17476. return true;
  17477. };
  17478. // Statics
  17479. BoundingBox.Intersects = function (box0, box1) {
  17480. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  17481. return false;
  17482. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  17483. return false;
  17484. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  17485. return false;
  17486. return true;
  17487. };
  17488. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  17489. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  17490. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  17491. return (num <= (sphereRadius * sphereRadius));
  17492. };
  17493. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  17494. for (var p = 0; p < 6; p++) {
  17495. for (var i = 0; i < 8; i++) {
  17496. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  17497. return false;
  17498. }
  17499. }
  17500. }
  17501. return true;
  17502. };
  17503. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  17504. for (var p = 0; p < 6; p++) {
  17505. var inCount = 8;
  17506. for (var i = 0; i < 8; i++) {
  17507. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  17508. --inCount;
  17509. }
  17510. else {
  17511. break;
  17512. }
  17513. }
  17514. if (inCount === 0)
  17515. return false;
  17516. }
  17517. return true;
  17518. };
  17519. return BoundingBox;
  17520. }());
  17521. BABYLON.BoundingBox = BoundingBox;
  17522. })(BABYLON || (BABYLON = {}));
  17523. //# sourceMappingURL=babylon.boundingBox.js.map
  17524. "use strict";
  17525. var BABYLON;
  17526. (function (BABYLON) {
  17527. var computeBoxExtents = function (axis, box) {
  17528. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  17529. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  17530. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  17531. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  17532. var r = r0 + r1 + r2;
  17533. return {
  17534. min: p - r,
  17535. max: p + r
  17536. };
  17537. };
  17538. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  17539. var axisOverlap = function (axis, box0, box1) {
  17540. var result0 = computeBoxExtents(axis, box0);
  17541. var result1 = computeBoxExtents(axis, box1);
  17542. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  17543. };
  17544. var BoundingInfo = /** @class */ (function () {
  17545. function BoundingInfo(minimum, maximum) {
  17546. this.minimum = minimum;
  17547. this.maximum = maximum;
  17548. this._isLocked = false;
  17549. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  17550. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  17551. }
  17552. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  17553. get: function () {
  17554. return this._isLocked;
  17555. },
  17556. set: function (value) {
  17557. this._isLocked = value;
  17558. },
  17559. enumerable: true,
  17560. configurable: true
  17561. });
  17562. // Methods
  17563. BoundingInfo.prototype.update = function (world) {
  17564. if (this._isLocked) {
  17565. return;
  17566. }
  17567. this.boundingBox._update(world);
  17568. this.boundingSphere._update(world);
  17569. };
  17570. /**
  17571. * Recreate the bounding info to be centered around a specific point given a specific extend.
  17572. * @param center New center of the bounding info
  17573. * @param extend New extend of the bounding info
  17574. */
  17575. BoundingInfo.prototype.centerOn = function (center, extend) {
  17576. this.minimum = center.subtract(extend);
  17577. this.maximum = center.add(extend);
  17578. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  17579. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  17580. return this;
  17581. };
  17582. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  17583. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  17584. return false;
  17585. return this.boundingBox.isInFrustum(frustumPlanes);
  17586. };
  17587. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  17588. /**
  17589. * Gets the world distance between the min and max points of the bounding box
  17590. */
  17591. get: function () {
  17592. var boundingBox = this.boundingBox;
  17593. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  17594. return size.length();
  17595. },
  17596. enumerable: true,
  17597. configurable: true
  17598. });
  17599. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  17600. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  17601. };
  17602. BoundingInfo.prototype._checkCollision = function (collider) {
  17603. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  17604. };
  17605. BoundingInfo.prototype.intersectsPoint = function (point) {
  17606. if (!this.boundingSphere.centerWorld) {
  17607. return false;
  17608. }
  17609. if (!this.boundingSphere.intersectsPoint(point)) {
  17610. return false;
  17611. }
  17612. if (!this.boundingBox.intersectsPoint(point)) {
  17613. return false;
  17614. }
  17615. return true;
  17616. };
  17617. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  17618. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  17619. return false;
  17620. }
  17621. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  17622. return false;
  17623. }
  17624. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  17625. return false;
  17626. }
  17627. if (!precise) {
  17628. return true;
  17629. }
  17630. var box0 = this.boundingBox;
  17631. var box1 = boundingInfo.boundingBox;
  17632. if (!axisOverlap(box0.directions[0], box0, box1))
  17633. return false;
  17634. if (!axisOverlap(box0.directions[1], box0, box1))
  17635. return false;
  17636. if (!axisOverlap(box0.directions[2], box0, box1))
  17637. return false;
  17638. if (!axisOverlap(box1.directions[0], box0, box1))
  17639. return false;
  17640. if (!axisOverlap(box1.directions[1], box0, box1))
  17641. return false;
  17642. if (!axisOverlap(box1.directions[2], box0, box1))
  17643. return false;
  17644. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  17645. return false;
  17646. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  17647. return false;
  17648. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  17649. return false;
  17650. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  17651. return false;
  17652. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  17653. return false;
  17654. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  17655. return false;
  17656. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  17657. return false;
  17658. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  17659. return false;
  17660. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  17661. return false;
  17662. return true;
  17663. };
  17664. return BoundingInfo;
  17665. }());
  17666. BABYLON.BoundingInfo = BoundingInfo;
  17667. })(BABYLON || (BABYLON = {}));
  17668. //# sourceMappingURL=babylon.boundingInfo.js.map
  17669. "use strict";
  17670. var BABYLON;
  17671. (function (BABYLON) {
  17672. var TransformNode = /** @class */ (function (_super) {
  17673. __extends(TransformNode, _super);
  17674. function TransformNode(name, scene, isPure) {
  17675. if (scene === void 0) { scene = null; }
  17676. if (isPure === void 0) { isPure = true; }
  17677. var _this = _super.call(this, name, scene) || this;
  17678. _this._forward = new BABYLON.Vector3(0, 0, 1);
  17679. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  17680. _this._up = new BABYLON.Vector3(0, 1, 0);
  17681. _this._right = new BABYLON.Vector3(1, 0, 0);
  17682. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  17683. // Properties
  17684. _this._rotation = BABYLON.Vector3.Zero();
  17685. _this._scaling = BABYLON.Vector3.One();
  17686. _this._isDirty = false;
  17687. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  17688. _this.scalingDeterminant = 1;
  17689. _this.infiniteDistance = false;
  17690. _this.position = BABYLON.Vector3.Zero();
  17691. _this._localWorld = BABYLON.Matrix.Zero();
  17692. _this._worldMatrix = BABYLON.Matrix.Zero();
  17693. _this._worldMatrixDeterminant = 0;
  17694. _this._absolutePosition = BABYLON.Vector3.Zero();
  17695. _this._pivotMatrix = BABYLON.Matrix.Identity();
  17696. _this._postMultiplyPivotMatrix = false;
  17697. _this._isWorldMatrixFrozen = false;
  17698. /**
  17699. * An event triggered after the world matrix is updated
  17700. */
  17701. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  17702. _this._nonUniformScaling = false;
  17703. if (isPure) {
  17704. _this.getScene().addTransformNode(_this);
  17705. }
  17706. return _this;
  17707. }
  17708. /**
  17709. * Gets a string idenfifying the name of the class
  17710. * @returns "TransformNode" string
  17711. */
  17712. TransformNode.prototype.getClassName = function () {
  17713. return "TransformNode";
  17714. };
  17715. Object.defineProperty(TransformNode.prototype, "rotation", {
  17716. /**
  17717. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  17718. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  17719. * Default : (0.0, 0.0, 0.0)
  17720. */
  17721. get: function () {
  17722. return this._rotation;
  17723. },
  17724. set: function (newRotation) {
  17725. this._rotation = newRotation;
  17726. },
  17727. enumerable: true,
  17728. configurable: true
  17729. });
  17730. Object.defineProperty(TransformNode.prototype, "scaling", {
  17731. /**
  17732. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17733. * Default : (1.0, 1.0, 1.0)
  17734. */
  17735. get: function () {
  17736. return this._scaling;
  17737. },
  17738. /**
  17739. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17740. * Default : (1.0, 1.0, 1.0)
  17741. */
  17742. set: function (newScaling) {
  17743. this._scaling = newScaling;
  17744. },
  17745. enumerable: true,
  17746. configurable: true
  17747. });
  17748. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  17749. /**
  17750. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  17751. * It's null by default.
  17752. * 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)
  17753. */
  17754. get: function () {
  17755. return this._rotationQuaternion;
  17756. },
  17757. set: function (quaternion) {
  17758. this._rotationQuaternion = quaternion;
  17759. //reset the rotation vector.
  17760. if (quaternion && this.rotation.length()) {
  17761. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  17762. }
  17763. },
  17764. enumerable: true,
  17765. configurable: true
  17766. });
  17767. Object.defineProperty(TransformNode.prototype, "forward", {
  17768. /**
  17769. * The forward direction of that transform in world space.
  17770. */
  17771. get: function () {
  17772. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  17773. },
  17774. enumerable: true,
  17775. configurable: true
  17776. });
  17777. Object.defineProperty(TransformNode.prototype, "up", {
  17778. /**
  17779. * The up direction of that transform in world space.
  17780. */
  17781. get: function () {
  17782. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  17783. },
  17784. enumerable: true,
  17785. configurable: true
  17786. });
  17787. Object.defineProperty(TransformNode.prototype, "right", {
  17788. /**
  17789. * The right direction of that transform in world space.
  17790. */
  17791. get: function () {
  17792. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  17793. },
  17794. enumerable: true,
  17795. configurable: true
  17796. });
  17797. /**
  17798. * Returns the latest update of the World matrix
  17799. * Returns a Matrix.
  17800. */
  17801. TransformNode.prototype.getWorldMatrix = function () {
  17802. if (this._currentRenderId !== this.getScene().getRenderId()) {
  17803. this.computeWorldMatrix();
  17804. }
  17805. return this._worldMatrix;
  17806. };
  17807. /**
  17808. * Returns the latest update of the World matrix determinant.
  17809. */
  17810. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  17811. return this._worldMatrixDeterminant;
  17812. };
  17813. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  17814. /**
  17815. * Returns directly the latest state of the mesh World matrix.
  17816. * A Matrix is returned.
  17817. */
  17818. get: function () {
  17819. return this._worldMatrix;
  17820. },
  17821. enumerable: true,
  17822. configurable: true
  17823. });
  17824. /**
  17825. * Copies the paramater passed Matrix into the mesh Pose matrix.
  17826. * Returns the TransformNode.
  17827. */
  17828. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  17829. this._poseMatrix.copyFrom(matrix);
  17830. return this;
  17831. };
  17832. /**
  17833. * Returns the mesh Pose matrix.
  17834. * Returned object : Matrix
  17835. */
  17836. TransformNode.prototype.getPoseMatrix = function () {
  17837. return this._poseMatrix;
  17838. };
  17839. TransformNode.prototype._isSynchronized = function () {
  17840. if (this._isDirty) {
  17841. return false;
  17842. }
  17843. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  17844. return false;
  17845. if (this._cache.pivotMatrixUpdated) {
  17846. return false;
  17847. }
  17848. if (this.infiniteDistance) {
  17849. return false;
  17850. }
  17851. if (!this._cache.position.equals(this.position))
  17852. return false;
  17853. if (this.rotationQuaternion) {
  17854. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  17855. return false;
  17856. }
  17857. if (!this._cache.rotation.equals(this.rotation))
  17858. return false;
  17859. if (!this._cache.scaling.equals(this.scaling))
  17860. return false;
  17861. return true;
  17862. };
  17863. TransformNode.prototype._initCache = function () {
  17864. _super.prototype._initCache.call(this);
  17865. this._cache.localMatrixUpdated = false;
  17866. this._cache.position = BABYLON.Vector3.Zero();
  17867. this._cache.scaling = BABYLON.Vector3.Zero();
  17868. this._cache.rotation = BABYLON.Vector3.Zero();
  17869. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  17870. this._cache.billboardMode = -1;
  17871. };
  17872. TransformNode.prototype.markAsDirty = function (property) {
  17873. if (property === "rotation") {
  17874. this.rotationQuaternion = null;
  17875. }
  17876. this._currentRenderId = Number.MAX_VALUE;
  17877. this._isDirty = true;
  17878. return this;
  17879. };
  17880. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  17881. /**
  17882. * Returns the current mesh absolute position.
  17883. * Retuns a Vector3.
  17884. */
  17885. get: function () {
  17886. return this._absolutePosition;
  17887. },
  17888. enumerable: true,
  17889. configurable: true
  17890. });
  17891. /**
  17892. * Sets a new matrix to apply before all other transformation
  17893. * @param matrix defines the transform matrix
  17894. * @returns the current TransformNode
  17895. */
  17896. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  17897. return this.setPivotMatrix(matrix, false);
  17898. };
  17899. /**
  17900. * Sets a new pivot matrix to the current node
  17901. * @param matrix defines the new pivot matrix to use
  17902. * @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
  17903. * @returns the current TransformNode
  17904. */
  17905. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  17906. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  17907. this._pivotMatrix = matrix.clone();
  17908. this._cache.pivotMatrixUpdated = true;
  17909. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  17910. if (this._postMultiplyPivotMatrix) {
  17911. if (!this._pivotMatrixInverse) {
  17912. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  17913. }
  17914. else {
  17915. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  17916. }
  17917. }
  17918. return this;
  17919. };
  17920. /**
  17921. * Returns the mesh pivot matrix.
  17922. * Default : Identity.
  17923. * A Matrix is returned.
  17924. */
  17925. TransformNode.prototype.getPivotMatrix = function () {
  17926. return this._pivotMatrix;
  17927. };
  17928. /**
  17929. * Prevents the World matrix to be computed any longer.
  17930. * Returns the TransformNode.
  17931. */
  17932. TransformNode.prototype.freezeWorldMatrix = function () {
  17933. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  17934. this.computeWorldMatrix(true);
  17935. this._isWorldMatrixFrozen = true;
  17936. return this;
  17937. };
  17938. /**
  17939. * Allows back the World matrix computation.
  17940. * Returns the TransformNode.
  17941. */
  17942. TransformNode.prototype.unfreezeWorldMatrix = function () {
  17943. this._isWorldMatrixFrozen = false;
  17944. this.computeWorldMatrix(true);
  17945. return this;
  17946. };
  17947. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  17948. /**
  17949. * True if the World matrix has been frozen.
  17950. * Returns a boolean.
  17951. */
  17952. get: function () {
  17953. return this._isWorldMatrixFrozen;
  17954. },
  17955. enumerable: true,
  17956. configurable: true
  17957. });
  17958. /**
  17959. * Retuns the mesh absolute position in the World.
  17960. * Returns a Vector3.
  17961. */
  17962. TransformNode.prototype.getAbsolutePosition = function () {
  17963. this.computeWorldMatrix();
  17964. return this._absolutePosition;
  17965. };
  17966. /**
  17967. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  17968. * Returns the TransformNode.
  17969. */
  17970. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  17971. if (!absolutePosition) {
  17972. return this;
  17973. }
  17974. var absolutePositionX;
  17975. var absolutePositionY;
  17976. var absolutePositionZ;
  17977. if (absolutePosition.x === undefined) {
  17978. if (arguments.length < 3) {
  17979. return this;
  17980. }
  17981. absolutePositionX = arguments[0];
  17982. absolutePositionY = arguments[1];
  17983. absolutePositionZ = arguments[2];
  17984. }
  17985. else {
  17986. absolutePositionX = absolutePosition.x;
  17987. absolutePositionY = absolutePosition.y;
  17988. absolutePositionZ = absolutePosition.z;
  17989. }
  17990. if (this.parent) {
  17991. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  17992. invertParentWorldMatrix.invert();
  17993. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  17994. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  17995. }
  17996. else {
  17997. this.position.x = absolutePositionX;
  17998. this.position.y = absolutePositionY;
  17999. this.position.z = absolutePositionZ;
  18000. }
  18001. return this;
  18002. };
  18003. /**
  18004. * Sets the mesh position in its local space.
  18005. * Returns the TransformNode.
  18006. */
  18007. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18008. this.computeWorldMatrix();
  18009. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18010. return this;
  18011. };
  18012. /**
  18013. * Returns the mesh position in the local space from the current World matrix values.
  18014. * Returns a new Vector3.
  18015. */
  18016. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18017. this.computeWorldMatrix();
  18018. var invLocalWorldMatrix = this._localWorld.clone();
  18019. invLocalWorldMatrix.invert();
  18020. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18021. };
  18022. /**
  18023. * Translates the mesh along the passed Vector3 in its local space.
  18024. * Returns the TransformNode.
  18025. */
  18026. TransformNode.prototype.locallyTranslate = function (vector3) {
  18027. this.computeWorldMatrix(true);
  18028. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18029. return this;
  18030. };
  18031. /**
  18032. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18033. * @param targetPoint the position (must be in same space as current mesh) to look at
  18034. * @param yawCor optional yaw (y-axis) correction in radians
  18035. * @param pitchCor optional pitch (x-axis) correction in radians
  18036. * @param rollCor optional roll (z-axis) correction in radians
  18037. * @param space the choosen space of the target
  18038. * @returns the TransformNode.
  18039. */
  18040. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18041. if (yawCor === void 0) { yawCor = 0; }
  18042. if (pitchCor === void 0) { pitchCor = 0; }
  18043. if (rollCor === void 0) { rollCor = 0; }
  18044. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18045. var dv = TransformNode._lookAtVectorCache;
  18046. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18047. targetPoint.subtractToRef(pos, dv);
  18048. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18049. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18050. var pitch = Math.atan2(dv.y, len);
  18051. if (this.rotationQuaternion) {
  18052. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18053. }
  18054. else {
  18055. this.rotation.x = pitch + pitchCor;
  18056. this.rotation.y = yaw + yawCor;
  18057. this.rotation.z = rollCor;
  18058. }
  18059. return this;
  18060. };
  18061. /**
  18062. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18063. * This Vector3 is expressed in the World space.
  18064. */
  18065. TransformNode.prototype.getDirection = function (localAxis) {
  18066. var result = BABYLON.Vector3.Zero();
  18067. this.getDirectionToRef(localAxis, result);
  18068. return result;
  18069. };
  18070. /**
  18071. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18072. * localAxis is expressed in the mesh local space.
  18073. * result is computed in the Wordl space from the mesh World matrix.
  18074. * Returns the TransformNode.
  18075. */
  18076. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18077. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18078. return this;
  18079. };
  18080. /**
  18081. * Sets a new pivot point to the current node
  18082. * @param point defines the new pivot point to use
  18083. * @param space defines if the point is in world or local space (local by default)
  18084. * @returns the current TransformNode
  18085. */
  18086. TransformNode.prototype.setPivotPoint = function (point, space) {
  18087. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18088. if (this.getScene().getRenderId() == 0) {
  18089. this.computeWorldMatrix(true);
  18090. }
  18091. var wm = this.getWorldMatrix();
  18092. if (space == BABYLON.Space.WORLD) {
  18093. var tmat = BABYLON.Tmp.Matrix[0];
  18094. wm.invertToRef(tmat);
  18095. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18096. }
  18097. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18098. };
  18099. /**
  18100. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18101. */
  18102. TransformNode.prototype.getPivotPoint = function () {
  18103. var point = BABYLON.Vector3.Zero();
  18104. this.getPivotPointToRef(point);
  18105. return point;
  18106. };
  18107. /**
  18108. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18109. * Returns the TransformNode.
  18110. */
  18111. TransformNode.prototype.getPivotPointToRef = function (result) {
  18112. result.x = -this._pivotMatrix.m[12];
  18113. result.y = -this._pivotMatrix.m[13];
  18114. result.z = -this._pivotMatrix.m[14];
  18115. return this;
  18116. };
  18117. /**
  18118. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18119. */
  18120. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18121. var point = BABYLON.Vector3.Zero();
  18122. this.getAbsolutePivotPointToRef(point);
  18123. return point;
  18124. };
  18125. /**
  18126. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18127. * Returns the TransformNode.
  18128. */
  18129. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18130. result.x = this._pivotMatrix.m[12];
  18131. result.y = this._pivotMatrix.m[13];
  18132. result.z = this._pivotMatrix.m[14];
  18133. this.getPivotPointToRef(result);
  18134. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18135. return this;
  18136. };
  18137. /**
  18138. * Defines the passed node as the parent of the current node.
  18139. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18140. * Returns the TransformNode.
  18141. */
  18142. TransformNode.prototype.setParent = function (node) {
  18143. if (node === null) {
  18144. var rotation = BABYLON.Tmp.Quaternion[0];
  18145. var position = BABYLON.Tmp.Vector3[0];
  18146. var scale = BABYLON.Tmp.Vector3[1];
  18147. if (this.parent && this.parent.computeWorldMatrix) {
  18148. this.parent.computeWorldMatrix(true);
  18149. }
  18150. this.computeWorldMatrix(true);
  18151. this.getWorldMatrix().decompose(scale, rotation, position);
  18152. if (this.rotationQuaternion) {
  18153. this.rotationQuaternion.copyFrom(rotation);
  18154. }
  18155. else {
  18156. rotation.toEulerAnglesToRef(this.rotation);
  18157. }
  18158. this.scaling.x = scale.x;
  18159. this.scaling.y = scale.y;
  18160. this.scaling.z = scale.z;
  18161. this.position.x = position.x;
  18162. this.position.y = position.y;
  18163. this.position.z = position.z;
  18164. }
  18165. else {
  18166. var rotation = BABYLON.Tmp.Quaternion[0];
  18167. var position = BABYLON.Tmp.Vector3[0];
  18168. var scale = BABYLON.Tmp.Vector3[1];
  18169. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18170. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18171. this.computeWorldMatrix(true);
  18172. node.computeWorldMatrix(true);
  18173. node.getWorldMatrix().invertToRef(invParentMatrix);
  18174. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18175. diffMatrix.decompose(scale, rotation, position);
  18176. if (this.rotationQuaternion) {
  18177. this.rotationQuaternion.copyFrom(rotation);
  18178. }
  18179. else {
  18180. rotation.toEulerAnglesToRef(this.rotation);
  18181. }
  18182. this.position.x = position.x;
  18183. this.position.y = position.y;
  18184. this.position.z = position.z;
  18185. this.scaling.x = scale.x;
  18186. this.scaling.y = scale.y;
  18187. this.scaling.z = scale.z;
  18188. }
  18189. this.parent = node;
  18190. return this;
  18191. };
  18192. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18193. get: function () {
  18194. return this._nonUniformScaling;
  18195. },
  18196. enumerable: true,
  18197. configurable: true
  18198. });
  18199. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18200. if (this._nonUniformScaling === value) {
  18201. return false;
  18202. }
  18203. this._nonUniformScaling = true;
  18204. return true;
  18205. };
  18206. /**
  18207. * Attach the current TransformNode to another TransformNode associated with a bone
  18208. * @param bone Bone affecting the TransformNode
  18209. * @param affectedTransformNode TransformNode associated with the bone
  18210. */
  18211. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18212. this._transformToBoneReferal = affectedTransformNode;
  18213. this.parent = bone;
  18214. if (bone.getWorldMatrix().determinant() < 0) {
  18215. this.scalingDeterminant *= -1;
  18216. }
  18217. return this;
  18218. };
  18219. TransformNode.prototype.detachFromBone = function () {
  18220. if (!this.parent) {
  18221. return this;
  18222. }
  18223. if (this.parent.getWorldMatrix().determinant() < 0) {
  18224. this.scalingDeterminant *= -1;
  18225. }
  18226. this._transformToBoneReferal = null;
  18227. this.parent = null;
  18228. return this;
  18229. };
  18230. /**
  18231. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  18232. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18233. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18234. * The passed axis is also normalized.
  18235. * Returns the TransformNode.
  18236. */
  18237. TransformNode.prototype.rotate = function (axis, amount, space) {
  18238. axis.normalize();
  18239. if (!this.rotationQuaternion) {
  18240. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18241. this.rotation = BABYLON.Vector3.Zero();
  18242. }
  18243. var rotationQuaternion;
  18244. if (!space || space === BABYLON.Space.LOCAL) {
  18245. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18246. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  18247. }
  18248. else {
  18249. if (this.parent) {
  18250. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18251. invertParentWorldMatrix.invert();
  18252. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  18253. }
  18254. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18255. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18256. }
  18257. return this;
  18258. };
  18259. /**
  18260. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  18261. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18262. * The passed axis is also normalized.
  18263. * Returns the TransformNode.
  18264. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  18265. */
  18266. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  18267. axis.normalize();
  18268. if (!this.rotationQuaternion) {
  18269. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18270. this.rotation.copyFromFloats(0, 0, 0);
  18271. }
  18272. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  18273. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  18274. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  18275. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  18276. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  18277. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  18278. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  18279. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  18280. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18281. return this;
  18282. };
  18283. /**
  18284. * Translates the mesh along the axis vector for the passed distance in the given space.
  18285. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18286. * Returns the TransformNode.
  18287. */
  18288. TransformNode.prototype.translate = function (axis, distance, space) {
  18289. var displacementVector = axis.scale(distance);
  18290. if (!space || space === BABYLON.Space.LOCAL) {
  18291. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  18292. this.setPositionWithLocalVector(tempV3);
  18293. }
  18294. else {
  18295. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  18296. }
  18297. return this;
  18298. };
  18299. /**
  18300. * Adds a rotation step to the mesh current rotation.
  18301. * x, y, z are Euler angles expressed in radians.
  18302. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  18303. * This means this rotation is made in the mesh local space only.
  18304. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  18305. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  18306. * ```javascript
  18307. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  18308. * ```
  18309. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  18310. * 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.
  18311. * Returns the TransformNode.
  18312. */
  18313. TransformNode.prototype.addRotation = function (x, y, z) {
  18314. var rotationQuaternion;
  18315. if (this.rotationQuaternion) {
  18316. rotationQuaternion = this.rotationQuaternion;
  18317. }
  18318. else {
  18319. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  18320. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  18321. }
  18322. var accumulation = BABYLON.Tmp.Quaternion[0];
  18323. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  18324. rotationQuaternion.multiplyInPlace(accumulation);
  18325. if (!this.rotationQuaternion) {
  18326. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  18327. }
  18328. return this;
  18329. };
  18330. /**
  18331. * Computes the mesh World matrix and returns it.
  18332. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  18333. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  18334. * If the parameter `force`is set to `true`, the actual computation is done.
  18335. * Returns the mesh World Matrix.
  18336. */
  18337. TransformNode.prototype.computeWorldMatrix = function (force) {
  18338. if (this._isWorldMatrixFrozen) {
  18339. return this._worldMatrix;
  18340. }
  18341. if (!force && this.isSynchronized(true)) {
  18342. this._currentRenderId = this.getScene().getRenderId();
  18343. return this._worldMatrix;
  18344. }
  18345. this._cache.position.copyFrom(this.position);
  18346. this._cache.scaling.copyFrom(this.scaling);
  18347. this._cache.pivotMatrixUpdated = false;
  18348. this._cache.billboardMode = this.billboardMode;
  18349. this._currentRenderId = this.getScene().getRenderId();
  18350. this._childRenderId = this.getScene().getRenderId();
  18351. this._isDirty = false;
  18352. // Scaling
  18353. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  18354. // Rotation
  18355. //rotate, if quaternion is set and rotation was used
  18356. if (this.rotationQuaternion) {
  18357. var len = this.rotation.length();
  18358. if (len) {
  18359. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  18360. this.rotation.copyFromFloats(0, 0, 0);
  18361. }
  18362. }
  18363. if (this.rotationQuaternion) {
  18364. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  18365. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  18366. }
  18367. else {
  18368. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  18369. this._cache.rotation.copyFrom(this.rotation);
  18370. }
  18371. // Translation
  18372. var camera = this.getScene().activeCamera;
  18373. if (this.infiniteDistance && !this.parent && camera) {
  18374. var cameraWorldMatrix = camera.getWorldMatrix();
  18375. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  18376. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  18377. }
  18378. else {
  18379. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  18380. }
  18381. // Composing transformations
  18382. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  18383. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  18384. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  18385. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  18386. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  18387. // Need to decompose each rotation here
  18388. var currentPosition = BABYLON.Tmp.Vector3[3];
  18389. if (this.parent && this.parent.getWorldMatrix) {
  18390. if (this._transformToBoneReferal) {
  18391. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18392. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  18393. }
  18394. else {
  18395. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  18396. }
  18397. }
  18398. else {
  18399. currentPosition.copyFrom(this.position);
  18400. }
  18401. currentPosition.subtractInPlace(camera.globalPosition);
  18402. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  18403. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  18404. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  18405. }
  18406. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  18407. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  18408. }
  18409. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  18410. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  18411. }
  18412. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  18413. }
  18414. else {
  18415. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  18416. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  18417. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  18418. }
  18419. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  18420. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  18421. }
  18422. // Local world
  18423. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  18424. // Parent
  18425. if (this.parent && this.parent.getWorldMatrix) {
  18426. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  18427. if (this._transformToBoneReferal) {
  18428. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18429. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  18430. }
  18431. else {
  18432. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  18433. }
  18434. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  18435. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  18436. this._worldMatrix.copyFrom(this._localWorld);
  18437. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  18438. }
  18439. else {
  18440. if (this._transformToBoneReferal) {
  18441. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18442. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  18443. }
  18444. else {
  18445. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  18446. }
  18447. }
  18448. this._markSyncedWithParent();
  18449. }
  18450. else {
  18451. this._worldMatrix.copyFrom(this._localWorld);
  18452. }
  18453. // Post multiply inverse of pivotMatrix
  18454. if (this._postMultiplyPivotMatrix) {
  18455. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  18456. }
  18457. // Normal matrix
  18458. if (this.scaling.isNonUniform) {
  18459. this._updateNonUniformScalingState(true);
  18460. }
  18461. else if (this.parent && this.parent._nonUniformScaling) {
  18462. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  18463. }
  18464. else {
  18465. this._updateNonUniformScalingState(false);
  18466. }
  18467. this._afterComputeWorldMatrix();
  18468. // Absolute position
  18469. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  18470. // Callbacks
  18471. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  18472. if (!this._poseMatrix) {
  18473. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  18474. }
  18475. // Cache the determinant
  18476. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  18477. return this._worldMatrix;
  18478. };
  18479. TransformNode.prototype._afterComputeWorldMatrix = function () {
  18480. };
  18481. /**
  18482. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  18483. * @param func: callback function to add
  18484. *
  18485. * Returns the TransformNode.
  18486. */
  18487. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  18488. this.onAfterWorldMatrixUpdateObservable.add(func);
  18489. return this;
  18490. };
  18491. /**
  18492. * Removes a registered callback function.
  18493. * Returns the TransformNode.
  18494. */
  18495. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  18496. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  18497. return this;
  18498. };
  18499. /**
  18500. * Clone the current transform node
  18501. * Returns the new transform node
  18502. * @param name Name of the new clone
  18503. * @param newParent New parent for the clone
  18504. * @param doNotCloneChildren Do not clone children hierarchy
  18505. */
  18506. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18507. var _this = this;
  18508. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  18509. result.name = name;
  18510. result.id = name;
  18511. if (newParent) {
  18512. result.parent = newParent;
  18513. }
  18514. if (!doNotCloneChildren) {
  18515. // Children
  18516. var directDescendants = this.getDescendants(true);
  18517. for (var index = 0; index < directDescendants.length; index++) {
  18518. var child = directDescendants[index];
  18519. if (child.clone) {
  18520. child.clone(name + "." + child.name, result);
  18521. }
  18522. }
  18523. }
  18524. return result;
  18525. };
  18526. TransformNode.prototype.serialize = function (currentSerializationObject) {
  18527. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  18528. serializationObject.type = this.getClassName();
  18529. // Parent
  18530. if (this.parent) {
  18531. serializationObject.parentId = this.parent.id;
  18532. }
  18533. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  18534. serializationObject.tags = BABYLON.Tags.GetTags(this);
  18535. }
  18536. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  18537. serializationObject.isEnabled = this.isEnabled();
  18538. // Parent
  18539. if (this.parent) {
  18540. serializationObject.parentId = this.parent.id;
  18541. }
  18542. return serializationObject;
  18543. };
  18544. // Statics
  18545. /**
  18546. * Returns a new TransformNode object parsed from the source provided.
  18547. * The parameter `parsedMesh` is the source.
  18548. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  18549. */
  18550. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  18551. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  18552. if (BABYLON.Tags) {
  18553. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  18554. }
  18555. if (parsedTransformNode.localMatrix) {
  18556. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  18557. }
  18558. else if (parsedTransformNode.pivotMatrix) {
  18559. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  18560. }
  18561. transformNode.setEnabled(parsedTransformNode.isEnabled);
  18562. // Parent
  18563. if (parsedTransformNode.parentId) {
  18564. transformNode._waitingParentId = parsedTransformNode.parentId;
  18565. }
  18566. return transformNode;
  18567. };
  18568. /**
  18569. * Releases resources associated with this transform node.
  18570. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18571. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18572. */
  18573. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18574. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18575. // Animations
  18576. this.getScene().stopAnimation(this);
  18577. // Remove from scene
  18578. this.getScene().removeTransformNode(this);
  18579. this.onAfterWorldMatrixUpdateObservable.clear();
  18580. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  18581. };
  18582. // Statics
  18583. TransformNode.BILLBOARDMODE_NONE = 0;
  18584. TransformNode.BILLBOARDMODE_X = 1;
  18585. TransformNode.BILLBOARDMODE_Y = 2;
  18586. TransformNode.BILLBOARDMODE_Z = 4;
  18587. TransformNode.BILLBOARDMODE_ALL = 7;
  18588. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  18589. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  18590. __decorate([
  18591. BABYLON.serializeAsVector3()
  18592. ], TransformNode.prototype, "_rotation", void 0);
  18593. __decorate([
  18594. BABYLON.serializeAsQuaternion()
  18595. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  18596. __decorate([
  18597. BABYLON.serializeAsVector3()
  18598. ], TransformNode.prototype, "_scaling", void 0);
  18599. __decorate([
  18600. BABYLON.serialize()
  18601. ], TransformNode.prototype, "billboardMode", void 0);
  18602. __decorate([
  18603. BABYLON.serialize()
  18604. ], TransformNode.prototype, "scalingDeterminant", void 0);
  18605. __decorate([
  18606. BABYLON.serialize()
  18607. ], TransformNode.prototype, "infiniteDistance", void 0);
  18608. __decorate([
  18609. BABYLON.serializeAsVector3()
  18610. ], TransformNode.prototype, "position", void 0);
  18611. return TransformNode;
  18612. }(BABYLON.Node));
  18613. BABYLON.TransformNode = TransformNode;
  18614. })(BABYLON || (BABYLON = {}));
  18615. //# sourceMappingURL=babylon.transformNode.js.map
  18616. "use strict";
  18617. var BABYLON;
  18618. (function (BABYLON) {
  18619. var AbstractMesh = /** @class */ (function (_super) {
  18620. __extends(AbstractMesh, _super);
  18621. // Constructor
  18622. function AbstractMesh(name, scene) {
  18623. if (scene === void 0) { scene = null; }
  18624. var _this = _super.call(this, name, scene, false) || this;
  18625. _this._facetNb = 0; // facet number
  18626. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  18627. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  18628. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  18629. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  18630. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  18631. _this._subDiv = {
  18632. max: 1,
  18633. X: 1,
  18634. Y: 1,
  18635. Z: 1
  18636. };
  18637. _this._facetDepthSort = false; // is the facet depth sort to be computed
  18638. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  18639. // Events
  18640. /**
  18641. * An event triggered when this mesh collides with another one
  18642. */
  18643. _this.onCollideObservable = new BABYLON.Observable();
  18644. /**
  18645. * An event triggered when the collision's position changes
  18646. */
  18647. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  18648. /**
  18649. * An event triggered when material is changed
  18650. */
  18651. _this.onMaterialChangedObservable = new BABYLON.Observable();
  18652. // Properties
  18653. _this.definedFacingForward = true; // orientation for POV movement & rotation
  18654. /**
  18655. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  18656. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  18657. * or
  18658. * 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.
  18659. * for more info check WebGl documentations
  18660. */
  18661. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  18662. /**
  18663. * 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:
  18664. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  18665. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  18666. * 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.
  18667. */
  18668. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  18669. /**
  18670. * 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.
  18671. * The default value is -1 which means don't break the query and wait till the result.
  18672. */
  18673. _this.occlusionRetryCount = -1;
  18674. _this._occlusionInternalRetryCounter = 0;
  18675. _this._isOccluded = false;
  18676. _this._isOcclusionQueryInProgress = false;
  18677. _this._visibility = 1.0;
  18678. _this.alphaIndex = Number.MAX_VALUE;
  18679. _this.isVisible = true;
  18680. _this.isPickable = true;
  18681. _this.showBoundingBox = false;
  18682. _this.showSubMeshesBoundingBox = false;
  18683. _this.isBlocker = false;
  18684. _this.enablePointerMoveEvents = false;
  18685. _this.renderingGroupId = 0;
  18686. _this._receiveShadows = false;
  18687. _this.renderOutline = false;
  18688. _this.outlineColor = BABYLON.Color3.Red();
  18689. _this.outlineWidth = 0.02;
  18690. _this.renderOverlay = false;
  18691. _this.overlayColor = BABYLON.Color3.Red();
  18692. _this.overlayAlpha = 0.5;
  18693. _this._hasVertexAlpha = false;
  18694. _this._useVertexColors = true;
  18695. _this._computeBonesUsingShaders = true;
  18696. _this._numBoneInfluencers = 4;
  18697. _this._applyFog = true;
  18698. _this.useOctreeForRenderingSelection = true;
  18699. _this.useOctreeForPicking = true;
  18700. _this.useOctreeForCollisions = true;
  18701. _this._layerMask = 0x0FFFFFFF;
  18702. /**
  18703. * True if the mesh must be rendered in any case.
  18704. */
  18705. _this.alwaysSelectAsActiveMesh = false;
  18706. /**
  18707. * This scene's action manager
  18708. */
  18709. _this.actionManager = null;
  18710. // Physics
  18711. _this.physicsImpostor = null;
  18712. // Collisions
  18713. _this._checkCollisions = false;
  18714. _this._collisionMask = -1;
  18715. _this._collisionGroup = -1;
  18716. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  18717. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  18718. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  18719. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  18720. // Edges
  18721. _this.edgesWidth = 1;
  18722. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  18723. // Cache
  18724. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  18725. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  18726. _this._renderId = 0;
  18727. _this._intersectionsInProgress = new Array();
  18728. _this._unIndexed = false;
  18729. _this._lightSources = new Array();
  18730. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  18731. if (collidedMesh === void 0) { collidedMesh = null; }
  18732. //TODO move this to the collision coordinator!
  18733. if (_this.getScene().workerCollisions)
  18734. newPosition.multiplyInPlace(_this._collider._radius);
  18735. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  18736. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  18737. _this.position.addInPlace(_this._diffPositionForCollisions);
  18738. }
  18739. if (collidedMesh) {
  18740. _this.onCollideObservable.notifyObservers(collidedMesh);
  18741. }
  18742. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  18743. };
  18744. _this.getScene().addMesh(_this);
  18745. _this._resyncLightSources();
  18746. return _this;
  18747. }
  18748. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  18749. get: function () {
  18750. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  18751. },
  18752. enumerable: true,
  18753. configurable: true
  18754. });
  18755. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  18756. get: function () {
  18757. return BABYLON.TransformNode.BILLBOARDMODE_X;
  18758. },
  18759. enumerable: true,
  18760. configurable: true
  18761. });
  18762. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  18763. get: function () {
  18764. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  18765. },
  18766. enumerable: true,
  18767. configurable: true
  18768. });
  18769. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  18770. get: function () {
  18771. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  18772. },
  18773. enumerable: true,
  18774. configurable: true
  18775. });
  18776. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  18777. get: function () {
  18778. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  18779. },
  18780. enumerable: true,
  18781. configurable: true
  18782. });
  18783. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  18784. /**
  18785. * Read-only : the number of facets in the mesh
  18786. */
  18787. get: function () {
  18788. return this._facetNb;
  18789. },
  18790. enumerable: true,
  18791. configurable: true
  18792. });
  18793. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  18794. /**
  18795. * The number (integer) of subdivisions per axis in the partioning space
  18796. */
  18797. get: function () {
  18798. return this._partitioningSubdivisions;
  18799. },
  18800. set: function (nb) {
  18801. this._partitioningSubdivisions = nb;
  18802. },
  18803. enumerable: true,
  18804. configurable: true
  18805. });
  18806. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  18807. /**
  18808. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  18809. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  18810. */
  18811. get: function () {
  18812. return this._partitioningBBoxRatio;
  18813. },
  18814. set: function (ratio) {
  18815. this._partitioningBBoxRatio = ratio;
  18816. },
  18817. enumerable: true,
  18818. configurable: true
  18819. });
  18820. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  18821. /**
  18822. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  18823. * Works only for updatable meshes.
  18824. * Doesn't work with multi-materials.
  18825. */
  18826. get: function () {
  18827. return this._facetDepthSort;
  18828. },
  18829. set: function (sort) {
  18830. this._facetDepthSort = sort;
  18831. },
  18832. enumerable: true,
  18833. configurable: true
  18834. });
  18835. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  18836. /**
  18837. * The location (Vector3) where the facet depth sort must be computed from.
  18838. * By default, the active camera position.
  18839. * Used only when facet depth sort is enabled.
  18840. */
  18841. get: function () {
  18842. return this._facetDepthSortFrom;
  18843. },
  18844. set: function (location) {
  18845. this._facetDepthSortFrom = location;
  18846. },
  18847. enumerable: true,
  18848. configurable: true
  18849. });
  18850. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  18851. /**
  18852. * Read-only boolean : is the feature facetData enabled ?
  18853. */
  18854. get: function () {
  18855. return this._facetDataEnabled;
  18856. },
  18857. enumerable: true,
  18858. configurable: true
  18859. });
  18860. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  18861. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  18862. return false;
  18863. }
  18864. this._markSubMeshesAsMiscDirty();
  18865. return true;
  18866. };
  18867. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  18868. set: function (callback) {
  18869. if (this._onCollideObserver) {
  18870. this.onCollideObservable.remove(this._onCollideObserver);
  18871. }
  18872. this._onCollideObserver = this.onCollideObservable.add(callback);
  18873. },
  18874. enumerable: true,
  18875. configurable: true
  18876. });
  18877. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  18878. set: function (callback) {
  18879. if (this._onCollisionPositionChangeObserver) {
  18880. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  18881. }
  18882. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  18883. },
  18884. enumerable: true,
  18885. configurable: true
  18886. });
  18887. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  18888. /**
  18889. * 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.
  18890. */
  18891. get: function () {
  18892. return this._isOccluded;
  18893. },
  18894. set: function (value) {
  18895. this._isOccluded = value;
  18896. },
  18897. enumerable: true,
  18898. configurable: true
  18899. });
  18900. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  18901. /**
  18902. * Flag to check the progress status of the query
  18903. */
  18904. get: function () {
  18905. return this._isOcclusionQueryInProgress;
  18906. },
  18907. enumerable: true,
  18908. configurable: true
  18909. });
  18910. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  18911. /**
  18912. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  18913. */
  18914. get: function () {
  18915. return this._visibility;
  18916. },
  18917. /**
  18918. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  18919. */
  18920. set: function (value) {
  18921. if (this._visibility === value) {
  18922. return;
  18923. }
  18924. this._visibility = value;
  18925. this._markSubMeshesAsMiscDirty();
  18926. },
  18927. enumerable: true,
  18928. configurable: true
  18929. });
  18930. Object.defineProperty(AbstractMesh.prototype, "material", {
  18931. get: function () {
  18932. return this._material;
  18933. },
  18934. set: function (value) {
  18935. if (this._material === value) {
  18936. return;
  18937. }
  18938. this._material = value;
  18939. if (this.onMaterialChangedObservable.hasObservers) {
  18940. this.onMaterialChangedObservable.notifyObservers(this);
  18941. }
  18942. if (!this.subMeshes) {
  18943. return;
  18944. }
  18945. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  18946. var subMesh = _a[_i];
  18947. subMesh.setEffect(null);
  18948. }
  18949. },
  18950. enumerable: true,
  18951. configurable: true
  18952. });
  18953. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  18954. get: function () {
  18955. return this._receiveShadows;
  18956. },
  18957. set: function (value) {
  18958. if (this._receiveShadows === value) {
  18959. return;
  18960. }
  18961. this._receiveShadows = value;
  18962. this._markSubMeshesAsLightDirty();
  18963. },
  18964. enumerable: true,
  18965. configurable: true
  18966. });
  18967. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  18968. get: function () {
  18969. return this._hasVertexAlpha;
  18970. },
  18971. set: function (value) {
  18972. if (this._hasVertexAlpha === value) {
  18973. return;
  18974. }
  18975. this._hasVertexAlpha = value;
  18976. this._markSubMeshesAsAttributesDirty();
  18977. this._markSubMeshesAsMiscDirty();
  18978. },
  18979. enumerable: true,
  18980. configurable: true
  18981. });
  18982. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  18983. get: function () {
  18984. return this._useVertexColors;
  18985. },
  18986. set: function (value) {
  18987. if (this._useVertexColors === value) {
  18988. return;
  18989. }
  18990. this._useVertexColors = value;
  18991. this._markSubMeshesAsAttributesDirty();
  18992. },
  18993. enumerable: true,
  18994. configurable: true
  18995. });
  18996. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  18997. get: function () {
  18998. return this._computeBonesUsingShaders;
  18999. },
  19000. set: function (value) {
  19001. if (this._computeBonesUsingShaders === value) {
  19002. return;
  19003. }
  19004. this._computeBonesUsingShaders = value;
  19005. this._markSubMeshesAsAttributesDirty();
  19006. },
  19007. enumerable: true,
  19008. configurable: true
  19009. });
  19010. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19011. get: function () {
  19012. return this._numBoneInfluencers;
  19013. },
  19014. set: function (value) {
  19015. if (this._numBoneInfluencers === value) {
  19016. return;
  19017. }
  19018. this._numBoneInfluencers = value;
  19019. this._markSubMeshesAsAttributesDirty();
  19020. },
  19021. enumerable: true,
  19022. configurable: true
  19023. });
  19024. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19025. get: function () {
  19026. return this._applyFog;
  19027. },
  19028. set: function (value) {
  19029. if (this._applyFog === value) {
  19030. return;
  19031. }
  19032. this._applyFog = value;
  19033. this._markSubMeshesAsMiscDirty();
  19034. },
  19035. enumerable: true,
  19036. configurable: true
  19037. });
  19038. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19039. get: function () {
  19040. return this._layerMask;
  19041. },
  19042. set: function (value) {
  19043. if (value === this._layerMask) {
  19044. return;
  19045. }
  19046. this._layerMask = value;
  19047. this._resyncLightSources();
  19048. },
  19049. enumerable: true,
  19050. configurable: true
  19051. });
  19052. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19053. get: function () {
  19054. return this._collisionMask;
  19055. },
  19056. set: function (mask) {
  19057. this._collisionMask = !isNaN(mask) ? mask : -1;
  19058. },
  19059. enumerable: true,
  19060. configurable: true
  19061. });
  19062. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19063. get: function () {
  19064. return this._collisionGroup;
  19065. },
  19066. set: function (mask) {
  19067. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19068. },
  19069. enumerable: true,
  19070. configurable: true
  19071. });
  19072. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19073. get: function () {
  19074. return null;
  19075. },
  19076. enumerable: true,
  19077. configurable: true
  19078. });
  19079. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19080. get: function () {
  19081. return this._skeleton;
  19082. },
  19083. set: function (value) {
  19084. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19085. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19086. }
  19087. if (value && value.needInitialSkinMatrix) {
  19088. value._registerMeshWithPoseMatrix(this);
  19089. }
  19090. this._skeleton = value;
  19091. if (!this._skeleton) {
  19092. this._bonesTransformMatrices = null;
  19093. }
  19094. this._markSubMeshesAsAttributesDirty();
  19095. },
  19096. enumerable: true,
  19097. configurable: true
  19098. });
  19099. /**
  19100. * Returns the string "AbstractMesh"
  19101. */
  19102. AbstractMesh.prototype.getClassName = function () {
  19103. return "AbstractMesh";
  19104. };
  19105. /**
  19106. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19107. */
  19108. AbstractMesh.prototype.toString = function (fullDetails) {
  19109. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  19110. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  19111. if (this._skeleton) {
  19112. ret += ", skeleton: " + this._skeleton.name;
  19113. }
  19114. if (fullDetails) {
  19115. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  19116. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  19117. }
  19118. return ret;
  19119. };
  19120. AbstractMesh.prototype._rebuild = function () {
  19121. if (this._occlusionQuery) {
  19122. this._occlusionQuery = null;
  19123. }
  19124. if (this._edgesRenderer) {
  19125. this._edgesRenderer._rebuild();
  19126. }
  19127. if (!this.subMeshes) {
  19128. return;
  19129. }
  19130. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19131. var subMesh = _a[_i];
  19132. subMesh._rebuild();
  19133. }
  19134. };
  19135. AbstractMesh.prototype._resyncLightSources = function () {
  19136. this._lightSources.length = 0;
  19137. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  19138. var light = _a[_i];
  19139. if (!light.isEnabled()) {
  19140. continue;
  19141. }
  19142. if (light.canAffectMesh(this)) {
  19143. this._lightSources.push(light);
  19144. }
  19145. }
  19146. this._markSubMeshesAsLightDirty();
  19147. };
  19148. AbstractMesh.prototype._resyncLighSource = function (light) {
  19149. var isIn = light.isEnabled() && light.canAffectMesh(this);
  19150. var index = this._lightSources.indexOf(light);
  19151. if (index === -1) {
  19152. if (!isIn) {
  19153. return;
  19154. }
  19155. this._lightSources.push(light);
  19156. }
  19157. else {
  19158. if (isIn) {
  19159. return;
  19160. }
  19161. this._lightSources.splice(index, 1);
  19162. }
  19163. this._markSubMeshesAsLightDirty();
  19164. };
  19165. AbstractMesh.prototype._removeLightSource = function (light) {
  19166. var index = this._lightSources.indexOf(light);
  19167. if (index === -1) {
  19168. return;
  19169. }
  19170. this._lightSources.splice(index, 1);
  19171. this._markSubMeshesAsLightDirty();
  19172. };
  19173. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  19174. if (!this.subMeshes) {
  19175. return;
  19176. }
  19177. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19178. var subMesh = _a[_i];
  19179. if (subMesh._materialDefines) {
  19180. func(subMesh._materialDefines);
  19181. }
  19182. }
  19183. };
  19184. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  19185. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  19186. };
  19187. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  19188. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  19189. };
  19190. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  19191. if (!this.subMeshes) {
  19192. return;
  19193. }
  19194. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19195. var subMesh = _a[_i];
  19196. var material = subMesh.getMaterial();
  19197. if (material) {
  19198. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  19199. }
  19200. }
  19201. };
  19202. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  19203. /**
  19204. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  19205. * Default : (1.0, 1.0, 1.0)
  19206. */
  19207. get: function () {
  19208. return this._scaling;
  19209. },
  19210. /**
  19211. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  19212. * Default : (1.0, 1.0, 1.0)
  19213. */
  19214. set: function (newScaling) {
  19215. this._scaling = newScaling;
  19216. if (this.physicsImpostor) {
  19217. this.physicsImpostor.forceUpdate();
  19218. }
  19219. },
  19220. enumerable: true,
  19221. configurable: true
  19222. });
  19223. // Methods
  19224. /**
  19225. * Disables the mesh edger rendering mode.
  19226. * Returns the AbstractMesh.
  19227. */
  19228. AbstractMesh.prototype.disableEdgesRendering = function () {
  19229. if (this._edgesRenderer) {
  19230. this._edgesRenderer.dispose();
  19231. this._edgesRenderer = null;
  19232. }
  19233. return this;
  19234. };
  19235. /**
  19236. * Enables the edge rendering mode on the mesh.
  19237. * This mode makes the mesh edges visible.
  19238. * Returns the AbstractMesh.
  19239. */
  19240. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  19241. if (epsilon === void 0) { epsilon = 0.95; }
  19242. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  19243. this.disableEdgesRendering();
  19244. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  19245. return this;
  19246. };
  19247. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  19248. /**
  19249. * Returns true if the mesh is blocked. Used by the class Mesh.
  19250. * Returns the boolean `false` by default.
  19251. */
  19252. get: function () {
  19253. return false;
  19254. },
  19255. enumerable: true,
  19256. configurable: true
  19257. });
  19258. /**
  19259. * Returns the mesh itself by default, used by the class Mesh.
  19260. * Returned type : AbstractMesh
  19261. */
  19262. AbstractMesh.prototype.getLOD = function (camera) {
  19263. return this;
  19264. };
  19265. /**
  19266. * Returns 0 by default, used by the class Mesh.
  19267. * Returns an integer.
  19268. */
  19269. AbstractMesh.prototype.getTotalVertices = function () {
  19270. return 0;
  19271. };
  19272. /**
  19273. * Returns null by default, used by the class Mesh.
  19274. * Returned type : integer array
  19275. */
  19276. AbstractMesh.prototype.getIndices = function () {
  19277. return null;
  19278. };
  19279. /**
  19280. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  19281. * Returned type : float array or Float32Array
  19282. */
  19283. AbstractMesh.prototype.getVerticesData = function (kind) {
  19284. return null;
  19285. };
  19286. /**
  19287. * Sets the vertex data of the mesh geometry for the requested `kind`.
  19288. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  19289. * The `data` are either a numeric array either a Float32Array.
  19290. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  19291. * 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).
  19292. * Note that a new underlying VertexBuffer object is created each call.
  19293. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  19294. *
  19295. * Possible `kind` values :
  19296. * - BABYLON.VertexBuffer.PositionKind
  19297. * - BABYLON.VertexBuffer.UVKind
  19298. * - BABYLON.VertexBuffer.UV2Kind
  19299. * - BABYLON.VertexBuffer.UV3Kind
  19300. * - BABYLON.VertexBuffer.UV4Kind
  19301. * - BABYLON.VertexBuffer.UV5Kind
  19302. * - BABYLON.VertexBuffer.UV6Kind
  19303. * - BABYLON.VertexBuffer.ColorKind
  19304. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19305. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19306. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19307. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19308. *
  19309. * Returns the Mesh.
  19310. */
  19311. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  19312. return this;
  19313. };
  19314. /**
  19315. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  19316. * If the mesh has no geometry, it is simply returned as it is.
  19317. * The `data` are either a numeric array either a Float32Array.
  19318. * No new underlying VertexBuffer object is created.
  19319. * 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.
  19320. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  19321. *
  19322. * Possible `kind` values :
  19323. * - BABYLON.VertexBuffer.PositionKind
  19324. * - BABYLON.VertexBuffer.UVKind
  19325. * - BABYLON.VertexBuffer.UV2Kind
  19326. * - BABYLON.VertexBuffer.UV3Kind
  19327. * - BABYLON.VertexBuffer.UV4Kind
  19328. * - BABYLON.VertexBuffer.UV5Kind
  19329. * - BABYLON.VertexBuffer.UV6Kind
  19330. * - BABYLON.VertexBuffer.ColorKind
  19331. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19332. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19333. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19334. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19335. *
  19336. * Returns the Mesh.
  19337. */
  19338. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  19339. return this;
  19340. };
  19341. /**
  19342. * Sets the mesh indices.
  19343. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  19344. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  19345. * This method creates a new index buffer each call.
  19346. * Returns the Mesh.
  19347. */
  19348. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  19349. return this;
  19350. };
  19351. /** Returns false by default, used by the class Mesh.
  19352. * Returns a boolean
  19353. */
  19354. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  19355. return false;
  19356. };
  19357. /**
  19358. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  19359. * Returns a BoundingInfo
  19360. */
  19361. AbstractMesh.prototype.getBoundingInfo = function () {
  19362. if (this._masterMesh) {
  19363. return this._masterMesh.getBoundingInfo();
  19364. }
  19365. if (!this._boundingInfo) {
  19366. // this._boundingInfo is being created here
  19367. this._updateBoundingInfo();
  19368. }
  19369. // cannot be null.
  19370. return this._boundingInfo;
  19371. };
  19372. /**
  19373. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  19374. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  19375. */
  19376. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  19377. if (includeDescendants === void 0) { includeDescendants = true; }
  19378. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  19379. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  19380. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  19381. if (maxDimension === 0) {
  19382. return this;
  19383. }
  19384. var scale = 1 / maxDimension;
  19385. this.scaling.scaleInPlace(scale);
  19386. return this;
  19387. };
  19388. /**
  19389. * Sets a mesh new object BoundingInfo.
  19390. * Returns the AbstractMesh.
  19391. */
  19392. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  19393. this._boundingInfo = boundingInfo;
  19394. return this;
  19395. };
  19396. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  19397. get: function () {
  19398. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  19399. },
  19400. enumerable: true,
  19401. configurable: true
  19402. });
  19403. AbstractMesh.prototype._preActivate = function () {
  19404. };
  19405. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  19406. };
  19407. AbstractMesh.prototype._activate = function (renderId) {
  19408. this._renderId = renderId;
  19409. };
  19410. /**
  19411. * Returns the latest update of the World matrix
  19412. * Returns a Matrix.
  19413. */
  19414. AbstractMesh.prototype.getWorldMatrix = function () {
  19415. if (this._masterMesh) {
  19416. return this._masterMesh.getWorldMatrix();
  19417. }
  19418. return _super.prototype.getWorldMatrix.call(this);
  19419. };
  19420. /**
  19421. * Returns the latest update of the World matrix determinant.
  19422. */
  19423. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  19424. if (this._masterMesh) {
  19425. return this._masterMesh._getWorldMatrixDeterminant();
  19426. }
  19427. return _super.prototype._getWorldMatrixDeterminant.call(this);
  19428. };
  19429. // ================================== Point of View Movement =================================
  19430. /**
  19431. * Perform relative position change from the point of view of behind the front of the mesh.
  19432. * This is performed taking into account the meshes current rotation, so you do not have to care.
  19433. * Supports definition of mesh facing forward or backward.
  19434. * @param {number} amountRight
  19435. * @param {number} amountUp
  19436. * @param {number} amountForward
  19437. *
  19438. * Returns the AbstractMesh.
  19439. */
  19440. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  19441. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  19442. return this;
  19443. };
  19444. /**
  19445. * Calculate relative position change from the point of view of behind the front of the mesh.
  19446. * This is performed taking into account the meshes current rotation, so you do not have to care.
  19447. * Supports definition of mesh facing forward or backward.
  19448. * @param {number} amountRight
  19449. * @param {number} amountUp
  19450. * @param {number} amountForward
  19451. *
  19452. * Returns a new Vector3.
  19453. */
  19454. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  19455. var rotMatrix = new BABYLON.Matrix();
  19456. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19457. rotQuaternion.toRotationMatrix(rotMatrix);
  19458. var translationDelta = BABYLON.Vector3.Zero();
  19459. var defForwardMult = this.definedFacingForward ? -1 : 1;
  19460. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  19461. return translationDelta;
  19462. };
  19463. // ================================== Point of View Rotation =================================
  19464. /**
  19465. * Perform relative rotation change from the point of view of behind the front of the mesh.
  19466. * Supports definition of mesh facing forward or backward.
  19467. * @param {number} flipBack
  19468. * @param {number} twirlClockwise
  19469. * @param {number} tiltRight
  19470. *
  19471. * Returns the AbstractMesh.
  19472. */
  19473. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  19474. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  19475. return this;
  19476. };
  19477. /**
  19478. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  19479. * Supports definition of mesh facing forward or backward.
  19480. * @param {number} flipBack
  19481. * @param {number} twirlClockwise
  19482. * @param {number} tiltRight
  19483. *
  19484. * Returns a new Vector3.
  19485. */
  19486. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  19487. var defForwardMult = this.definedFacingForward ? 1 : -1;
  19488. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  19489. };
  19490. /**
  19491. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  19492. * @param includeDescendants Include bounding info from descendants as well (true by default).
  19493. */
  19494. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  19495. if (includeDescendants === void 0) { includeDescendants = true; }
  19496. this.computeWorldMatrix(true);
  19497. var min;
  19498. var max;
  19499. var boundingInfo = this.getBoundingInfo();
  19500. if (!this.subMeshes) {
  19501. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19502. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  19503. }
  19504. else {
  19505. min = boundingInfo.boundingBox.minimumWorld;
  19506. max = boundingInfo.boundingBox.maximumWorld;
  19507. }
  19508. if (includeDescendants) {
  19509. var descendants = this.getDescendants(false);
  19510. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  19511. var descendant = descendants_1[_i];
  19512. var childMesh = descendant;
  19513. childMesh.computeWorldMatrix(true);
  19514. //make sure we have the needed params to get mix and max
  19515. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  19516. continue;
  19517. }
  19518. var childBoundingInfo = childMesh.getBoundingInfo();
  19519. var boundingBox = childBoundingInfo.boundingBox;
  19520. var minBox = boundingBox.minimumWorld;
  19521. var maxBox = boundingBox.maximumWorld;
  19522. BABYLON.Tools.CheckExtends(minBox, min, max);
  19523. BABYLON.Tools.CheckExtends(maxBox, min, max);
  19524. }
  19525. }
  19526. return {
  19527. min: min,
  19528. max: max
  19529. };
  19530. };
  19531. /**
  19532. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  19533. * Returns the AbstractMesh.
  19534. */
  19535. AbstractMesh.prototype._updateBoundingInfo = function () {
  19536. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  19537. this._boundingInfo.update(this.worldMatrixFromCache);
  19538. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  19539. return this;
  19540. };
  19541. /**
  19542. * Update a mesh's children BoundingInfo objects only.
  19543. * Returns the AbstractMesh.
  19544. */
  19545. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  19546. if (!this.subMeshes) {
  19547. return this;
  19548. }
  19549. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  19550. var subMesh = this.subMeshes[subIndex];
  19551. if (!subMesh.IsGlobal) {
  19552. subMesh.updateBoundingInfo(matrix);
  19553. }
  19554. }
  19555. return this;
  19556. };
  19557. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  19558. // Bounding info
  19559. this._updateBoundingInfo();
  19560. };
  19561. /**
  19562. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  19563. * A mesh is in the frustum if its bounding box intersects the frustum.
  19564. * Boolean returned.
  19565. */
  19566. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  19567. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  19568. };
  19569. /**
  19570. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  19571. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  19572. * Boolean returned.
  19573. */
  19574. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  19575. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  19576. ;
  19577. };
  19578. /**
  19579. * True if the mesh intersects another mesh or a SolidParticle object.
  19580. * 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)
  19581. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  19582. * Returns a boolean.
  19583. */
  19584. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  19585. if (precise === void 0) { precise = false; }
  19586. if (!this._boundingInfo || !mesh._boundingInfo) {
  19587. return false;
  19588. }
  19589. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  19590. return true;
  19591. }
  19592. if (includeDescendants) {
  19593. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  19594. var child = _a[_i];
  19595. if (child.intersectsMesh(mesh, precise, true)) {
  19596. return true;
  19597. }
  19598. }
  19599. }
  19600. return false;
  19601. };
  19602. /**
  19603. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  19604. * Returns a boolean.
  19605. */
  19606. AbstractMesh.prototype.intersectsPoint = function (point) {
  19607. if (!this._boundingInfo) {
  19608. return false;
  19609. }
  19610. return this._boundingInfo.intersectsPoint(point);
  19611. };
  19612. AbstractMesh.prototype.getPhysicsImpostor = function () {
  19613. return this.physicsImpostor;
  19614. };
  19615. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  19616. if (camera === void 0) { camera = null; }
  19617. if (!camera) {
  19618. camera = this.getScene().activeCamera;
  19619. }
  19620. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  19621. };
  19622. /**
  19623. * Returns the distance from the mesh to the active camera.
  19624. * Returns a float.
  19625. */
  19626. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  19627. if (camera === void 0) { camera = null; }
  19628. if (!camera) {
  19629. camera = this.getScene().activeCamera;
  19630. }
  19631. return this.absolutePosition.subtract(camera.position).length();
  19632. };
  19633. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  19634. if (!this.physicsImpostor) {
  19635. return this;
  19636. }
  19637. this.physicsImpostor.applyImpulse(force, contactPoint);
  19638. return this;
  19639. };
  19640. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  19641. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  19642. return this;
  19643. }
  19644. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  19645. mainPivot: pivot1,
  19646. connectedPivot: pivot2,
  19647. nativeParams: options
  19648. });
  19649. return this;
  19650. };
  19651. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  19652. // Collisions
  19653. /**
  19654. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  19655. * Default `false`.
  19656. */
  19657. get: function () {
  19658. return this._checkCollisions;
  19659. },
  19660. set: function (collisionEnabled) {
  19661. this._checkCollisions = collisionEnabled;
  19662. if (this.getScene().workerCollisions) {
  19663. this.getScene().collisionCoordinator.onMeshUpdated(this);
  19664. }
  19665. },
  19666. enumerable: true,
  19667. configurable: true
  19668. });
  19669. Object.defineProperty(AbstractMesh.prototype, "collider", {
  19670. /**
  19671. * Gets Collider object used to compute collisions (not physics)
  19672. */
  19673. get: function () {
  19674. return this._collider;
  19675. },
  19676. enumerable: true,
  19677. configurable: true
  19678. });
  19679. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  19680. var globalPosition = this.getAbsolutePosition();
  19681. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  19682. if (!this._collider) {
  19683. this._collider = new BABYLON.Collider();
  19684. }
  19685. this._collider._radius = this.ellipsoid;
  19686. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  19687. return this;
  19688. };
  19689. // Submeshes octree
  19690. /**
  19691. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  19692. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  19693. * Returns an Octree of submeshes.
  19694. */
  19695. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  19696. if (maxCapacity === void 0) { maxCapacity = 64; }
  19697. if (maxDepth === void 0) { maxDepth = 2; }
  19698. if (!this._submeshesOctree) {
  19699. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  19700. }
  19701. this.computeWorldMatrix(true);
  19702. var boundingInfo = this.getBoundingInfo();
  19703. // Update octree
  19704. var bbox = boundingInfo.boundingBox;
  19705. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  19706. return this._submeshesOctree;
  19707. };
  19708. // Collisions
  19709. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  19710. this._generatePointsArray();
  19711. if (!this._positions) {
  19712. return this;
  19713. }
  19714. // Transformation
  19715. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  19716. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  19717. subMesh._lastColliderWorldVertices = [];
  19718. subMesh._trianglePlanes = [];
  19719. var start = subMesh.verticesStart;
  19720. var end = (subMesh.verticesStart + subMesh.verticesCount);
  19721. for (var i = start; i < end; i++) {
  19722. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  19723. }
  19724. }
  19725. // Collide
  19726. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  19727. if (collider.collisionFound) {
  19728. collider.collidedMesh = this;
  19729. }
  19730. return this;
  19731. };
  19732. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  19733. var subMeshes;
  19734. var len;
  19735. // Octrees
  19736. if (this._submeshesOctree && this.useOctreeForCollisions) {
  19737. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  19738. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  19739. len = intersections.length;
  19740. subMeshes = intersections.data;
  19741. }
  19742. else {
  19743. subMeshes = this.subMeshes;
  19744. len = subMeshes.length;
  19745. }
  19746. for (var index = 0; index < len; index++) {
  19747. var subMesh = subMeshes[index];
  19748. // Bounding test
  19749. if (len > 1 && !subMesh._checkCollision(collider))
  19750. continue;
  19751. this._collideForSubMesh(subMesh, transformMatrix, collider);
  19752. }
  19753. return this;
  19754. };
  19755. AbstractMesh.prototype._checkCollision = function (collider) {
  19756. // Bounding box test
  19757. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  19758. return this;
  19759. // Transformation matrix
  19760. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  19761. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  19762. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  19763. return this;
  19764. };
  19765. // Picking
  19766. AbstractMesh.prototype._generatePointsArray = function () {
  19767. return false;
  19768. };
  19769. /**
  19770. * Checks if the passed Ray intersects with the mesh.
  19771. * Returns an object PickingInfo.
  19772. */
  19773. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  19774. var pickingInfo = new BABYLON.PickingInfo();
  19775. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  19776. return pickingInfo;
  19777. }
  19778. if (!this._generatePointsArray()) {
  19779. return pickingInfo;
  19780. }
  19781. var intersectInfo = null;
  19782. // Octrees
  19783. var subMeshes;
  19784. var len;
  19785. if (this._submeshesOctree && this.useOctreeForPicking) {
  19786. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  19787. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  19788. len = intersections.length;
  19789. subMeshes = intersections.data;
  19790. }
  19791. else {
  19792. subMeshes = this.subMeshes;
  19793. len = subMeshes.length;
  19794. }
  19795. for (var index = 0; index < len; index++) {
  19796. var subMesh = subMeshes[index];
  19797. // Bounding test
  19798. if (len > 1 && !subMesh.canIntersects(ray))
  19799. continue;
  19800. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  19801. if (currentIntersectInfo) {
  19802. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  19803. intersectInfo = currentIntersectInfo;
  19804. intersectInfo.subMeshId = index;
  19805. if (fastCheck) {
  19806. break;
  19807. }
  19808. }
  19809. }
  19810. }
  19811. if (intersectInfo) {
  19812. // Get picked point
  19813. var world = this.getWorldMatrix();
  19814. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  19815. var direction = ray.direction.clone();
  19816. direction = direction.scale(intersectInfo.distance);
  19817. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  19818. var pickedPoint = worldOrigin.add(worldDirection);
  19819. // Return result
  19820. pickingInfo.hit = true;
  19821. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  19822. pickingInfo.pickedPoint = pickedPoint;
  19823. pickingInfo.pickedMesh = this;
  19824. pickingInfo.bu = intersectInfo.bu || 0;
  19825. pickingInfo.bv = intersectInfo.bv || 0;
  19826. pickingInfo.faceId = intersectInfo.faceId;
  19827. pickingInfo.subMeshId = intersectInfo.subMeshId;
  19828. return pickingInfo;
  19829. }
  19830. return pickingInfo;
  19831. };
  19832. /**
  19833. * Clones the mesh, used by the class Mesh.
  19834. * Just returns `null` for an AbstractMesh.
  19835. */
  19836. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19837. return null;
  19838. };
  19839. /**
  19840. * Disposes all the mesh submeshes.
  19841. * Returns the AbstractMesh.
  19842. */
  19843. AbstractMesh.prototype.releaseSubMeshes = function () {
  19844. if (this.subMeshes) {
  19845. while (this.subMeshes.length) {
  19846. this.subMeshes[0].dispose();
  19847. }
  19848. }
  19849. else {
  19850. this.subMeshes = new Array();
  19851. }
  19852. return this;
  19853. };
  19854. /**
  19855. * Releases resources associated with this abstract mesh.
  19856. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19857. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19858. */
  19859. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19860. var _this = this;
  19861. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19862. var index;
  19863. // Smart Array Retainers.
  19864. this.getScene().freeActiveMeshes();
  19865. this.getScene().freeRenderingGroups();
  19866. // Action manager
  19867. if (this.actionManager !== undefined && this.actionManager !== null) {
  19868. this.actionManager.dispose();
  19869. this.actionManager = null;
  19870. }
  19871. // Skeleton
  19872. this._skeleton = null;
  19873. // Physics
  19874. if (this.physicsImpostor) {
  19875. this.physicsImpostor.dispose();
  19876. }
  19877. // Intersections in progress
  19878. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  19879. var other = this._intersectionsInProgress[index];
  19880. var pos = other._intersectionsInProgress.indexOf(this);
  19881. other._intersectionsInProgress.splice(pos, 1);
  19882. }
  19883. this._intersectionsInProgress = [];
  19884. // Lights
  19885. var lights = this.getScene().lights;
  19886. lights.forEach(function (light) {
  19887. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  19888. if (meshIndex !== -1) {
  19889. light.includedOnlyMeshes.splice(meshIndex, 1);
  19890. }
  19891. meshIndex = light.excludedMeshes.indexOf(_this);
  19892. if (meshIndex !== -1) {
  19893. light.excludedMeshes.splice(meshIndex, 1);
  19894. }
  19895. // Shadow generators
  19896. var generator = light.getShadowGenerator();
  19897. if (generator) {
  19898. var shadowMap = generator.getShadowMap();
  19899. if (shadowMap && shadowMap.renderList) {
  19900. meshIndex = shadowMap.renderList.indexOf(_this);
  19901. if (meshIndex !== -1) {
  19902. shadowMap.renderList.splice(meshIndex, 1);
  19903. }
  19904. }
  19905. }
  19906. });
  19907. // Edges
  19908. if (this._edgesRenderer) {
  19909. this._edgesRenderer.dispose();
  19910. this._edgesRenderer = null;
  19911. }
  19912. // SubMeshes
  19913. if (this.getClassName() !== "InstancedMesh") {
  19914. this.releaseSubMeshes();
  19915. }
  19916. // Octree
  19917. var sceneOctree = this.getScene().selectionOctree;
  19918. if (sceneOctree !== undefined && sceneOctree !== null) {
  19919. var index = sceneOctree.dynamicContent.indexOf(this);
  19920. if (index !== -1) {
  19921. sceneOctree.dynamicContent.splice(index, 1);
  19922. }
  19923. }
  19924. // Query
  19925. var engine = this.getScene().getEngine();
  19926. if (this._occlusionQuery) {
  19927. this._isOcclusionQueryInProgress = false;
  19928. engine.deleteQuery(this._occlusionQuery);
  19929. this._occlusionQuery = null;
  19930. }
  19931. // Engine
  19932. engine.wipeCaches();
  19933. // Remove from scene
  19934. this.getScene().removeMesh(this);
  19935. if (disposeMaterialAndTextures) {
  19936. if (this.material) {
  19937. this.material.dispose(false, true);
  19938. }
  19939. }
  19940. if (!doNotRecurse) {
  19941. // Particles
  19942. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  19943. if (this.getScene().particleSystems[index].emitter === this) {
  19944. this.getScene().particleSystems[index].dispose();
  19945. index--;
  19946. }
  19947. }
  19948. }
  19949. // facet data
  19950. if (this._facetDataEnabled) {
  19951. this.disableFacetData();
  19952. }
  19953. this.onAfterWorldMatrixUpdateObservable.clear();
  19954. this.onCollideObservable.clear();
  19955. this.onCollisionPositionChangeObservable.clear();
  19956. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19957. };
  19958. /**
  19959. * Adds the passed mesh as a child to the current mesh.
  19960. * Returns the AbstractMesh.
  19961. */
  19962. AbstractMesh.prototype.addChild = function (mesh) {
  19963. mesh.setParent(this);
  19964. return this;
  19965. };
  19966. /**
  19967. * Removes the passed mesh from the current mesh children list.
  19968. * Returns the AbstractMesh.
  19969. */
  19970. AbstractMesh.prototype.removeChild = function (mesh) {
  19971. mesh.setParent(null);
  19972. return this;
  19973. };
  19974. // Facet data
  19975. /**
  19976. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  19977. * Returns the AbstractMesh.
  19978. */
  19979. AbstractMesh.prototype._initFacetData = function () {
  19980. if (!this._facetNormals) {
  19981. this._facetNormals = new Array();
  19982. }
  19983. if (!this._facetPositions) {
  19984. this._facetPositions = new Array();
  19985. }
  19986. if (!this._facetPartitioning) {
  19987. this._facetPartitioning = new Array();
  19988. }
  19989. this._facetNb = (this.getIndices().length / 3) | 0;
  19990. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  19991. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  19992. for (var f = 0; f < this._facetNb; f++) {
  19993. this._facetNormals[f] = BABYLON.Vector3.Zero();
  19994. this._facetPositions[f] = BABYLON.Vector3.Zero();
  19995. }
  19996. this._facetDataEnabled = true;
  19997. return this;
  19998. };
  19999. /**
  20000. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20001. * This method can be called within the render loop.
  20002. * 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.
  20003. * Returns the AbstractMesh.
  20004. */
  20005. AbstractMesh.prototype.updateFacetData = function () {
  20006. if (!this._facetDataEnabled) {
  20007. this._initFacetData();
  20008. }
  20009. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20010. var indices = this.getIndices();
  20011. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20012. var bInfo = this.getBoundingInfo();
  20013. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  20014. // init arrays, matrix and sort function on first call
  20015. this._facetDepthSortEnabled = true;
  20016. if (indices instanceof Uint16Array) {
  20017. this._depthSortedIndices = new Uint16Array(indices);
  20018. }
  20019. else if (indices instanceof Uint32Array) {
  20020. this._depthSortedIndices = new Uint32Array(indices);
  20021. }
  20022. else {
  20023. var needs32bits = false;
  20024. for (var i = 0; i < indices.length; i++) {
  20025. if (indices[i] > 65535) {
  20026. needs32bits = true;
  20027. break;
  20028. }
  20029. }
  20030. if (needs32bits) {
  20031. this._depthSortedIndices = new Uint32Array(indices);
  20032. }
  20033. else {
  20034. this._depthSortedIndices = new Uint16Array(indices);
  20035. }
  20036. }
  20037. this._facetDepthSortFunction = function (f1, f2) {
  20038. return (f2.sqDistance - f1.sqDistance);
  20039. };
  20040. if (!this._facetDepthSortFrom) {
  20041. var camera = this.getScene().activeCamera;
  20042. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  20043. }
  20044. this._depthSortedFacets = [];
  20045. for (var f = 0; f < this._facetNb; f++) {
  20046. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  20047. this._depthSortedFacets.push(depthSortedFacet);
  20048. }
  20049. this._invertedMatrix = BABYLON.Matrix.Identity();
  20050. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  20051. }
  20052. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  20053. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  20054. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  20055. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  20056. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  20057. this._subDiv.max = this._partitioningSubdivisions;
  20058. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  20059. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  20060. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  20061. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  20062. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  20063. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  20064. // set the parameters for ComputeNormals()
  20065. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  20066. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  20067. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  20068. this._facetParameters.bInfo = bInfo;
  20069. this._facetParameters.bbSize = this._bbSize;
  20070. this._facetParameters.subDiv = this._subDiv;
  20071. this._facetParameters.ratio = this.partitioningBBoxRatio;
  20072. this._facetParameters.depthSort = this._facetDepthSort;
  20073. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20074. this.computeWorldMatrix(true);
  20075. this._worldMatrix.invertToRef(this._invertedMatrix);
  20076. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  20077. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  20078. }
  20079. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  20080. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  20081. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20082. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  20083. var l = (this._depthSortedIndices.length / 3) | 0;
  20084. for (var f = 0; f < l; f++) {
  20085. var sind = this._depthSortedFacets[f].ind;
  20086. this._depthSortedIndices[f * 3] = indices[sind];
  20087. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  20088. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  20089. }
  20090. this.updateIndices(this._depthSortedIndices);
  20091. }
  20092. return this;
  20093. };
  20094. /**
  20095. * Returns the facetLocalNormals array.
  20096. * The normals are expressed in the mesh local space.
  20097. */
  20098. AbstractMesh.prototype.getFacetLocalNormals = function () {
  20099. if (!this._facetNormals) {
  20100. this.updateFacetData();
  20101. }
  20102. return this._facetNormals;
  20103. };
  20104. /**
  20105. * Returns the facetLocalPositions array.
  20106. * The facet positions are expressed in the mesh local space.
  20107. */
  20108. AbstractMesh.prototype.getFacetLocalPositions = function () {
  20109. if (!this._facetPositions) {
  20110. this.updateFacetData();
  20111. }
  20112. return this._facetPositions;
  20113. };
  20114. /**
  20115. * Returns the facetLocalPartioning array.
  20116. */
  20117. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  20118. if (!this._facetPartitioning) {
  20119. this.updateFacetData();
  20120. }
  20121. return this._facetPartitioning;
  20122. };
  20123. /**
  20124. * Returns the i-th facet position in the world system.
  20125. * This method allocates a new Vector3 per call.
  20126. */
  20127. AbstractMesh.prototype.getFacetPosition = function (i) {
  20128. var pos = BABYLON.Vector3.Zero();
  20129. this.getFacetPositionToRef(i, pos);
  20130. return pos;
  20131. };
  20132. /**
  20133. * Sets the reference Vector3 with the i-th facet position in the world system.
  20134. * Returns the AbstractMesh.
  20135. */
  20136. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  20137. var localPos = (this.getFacetLocalPositions())[i];
  20138. var world = this.getWorldMatrix();
  20139. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  20140. return this;
  20141. };
  20142. /**
  20143. * Returns the i-th facet normal in the world system.
  20144. * This method allocates a new Vector3 per call.
  20145. */
  20146. AbstractMesh.prototype.getFacetNormal = function (i) {
  20147. var norm = BABYLON.Vector3.Zero();
  20148. this.getFacetNormalToRef(i, norm);
  20149. return norm;
  20150. };
  20151. /**
  20152. * Sets the reference Vector3 with the i-th facet normal in the world system.
  20153. * Returns the AbstractMesh.
  20154. */
  20155. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  20156. var localNorm = (this.getFacetLocalNormals())[i];
  20157. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  20158. return this;
  20159. };
  20160. /**
  20161. * 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).
  20162. */
  20163. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  20164. var bInfo = this.getBoundingInfo();
  20165. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  20166. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  20167. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  20168. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  20169. return null;
  20170. }
  20171. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  20172. };
  20173. /**
  20174. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  20175. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  20176. * 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.
  20177. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  20178. * 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.
  20179. */
  20180. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  20181. if (checkFace === void 0) { checkFace = false; }
  20182. if (facing === void 0) { facing = true; }
  20183. var world = this.getWorldMatrix();
  20184. var invMat = BABYLON.Tmp.Matrix[5];
  20185. world.invertToRef(invMat);
  20186. var invVect = BABYLON.Tmp.Vector3[8];
  20187. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  20188. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  20189. if (projected) {
  20190. // tranform the local computed projected vector to world coordinates
  20191. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  20192. }
  20193. return closest;
  20194. };
  20195. /**
  20196. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  20197. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  20198. * 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.
  20199. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  20200. * 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.
  20201. */
  20202. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  20203. if (checkFace === void 0) { checkFace = false; }
  20204. if (facing === void 0) { facing = true; }
  20205. var closest = null;
  20206. var tmpx = 0.0;
  20207. var tmpy = 0.0;
  20208. var tmpz = 0.0;
  20209. var d = 0.0; // tmp dot facet normal * facet position
  20210. var t0 = 0.0;
  20211. var projx = 0.0;
  20212. var projy = 0.0;
  20213. var projz = 0.0;
  20214. // Get all the facets in the same partitioning block than (x, y, z)
  20215. var facetPositions = this.getFacetLocalPositions();
  20216. var facetNormals = this.getFacetLocalNormals();
  20217. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  20218. if (!facetsInBlock) {
  20219. return null;
  20220. }
  20221. // Get the closest facet to (x, y, z)
  20222. var shortest = Number.MAX_VALUE; // init distance vars
  20223. var tmpDistance = shortest;
  20224. var fib; // current facet in the block
  20225. var norm; // current facet normal
  20226. var p0; // current facet barycenter position
  20227. // loop on all the facets in the current partitioning block
  20228. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  20229. fib = facetsInBlock[idx];
  20230. norm = facetNormals[fib];
  20231. p0 = facetPositions[fib];
  20232. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  20233. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  20234. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  20235. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  20236. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  20237. projx = x + norm.x * t0;
  20238. projy = y + norm.y * t0;
  20239. projz = z + norm.z * t0;
  20240. tmpx = projx - x;
  20241. tmpy = projy - y;
  20242. tmpz = projz - z;
  20243. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  20244. if (tmpDistance < shortest) {
  20245. shortest = tmpDistance;
  20246. closest = fib;
  20247. if (projected) {
  20248. projected.x = projx;
  20249. projected.y = projy;
  20250. projected.z = projz;
  20251. }
  20252. }
  20253. }
  20254. }
  20255. return closest;
  20256. };
  20257. /**
  20258. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  20259. */
  20260. AbstractMesh.prototype.getFacetDataParameters = function () {
  20261. return this._facetParameters;
  20262. };
  20263. /**
  20264. * Disables the feature FacetData and frees the related memory.
  20265. * Returns the AbstractMesh.
  20266. */
  20267. AbstractMesh.prototype.disableFacetData = function () {
  20268. if (this._facetDataEnabled) {
  20269. this._facetDataEnabled = false;
  20270. this._facetPositions = new Array();
  20271. this._facetNormals = new Array();
  20272. this._facetPartitioning = new Array();
  20273. this._facetParameters = null;
  20274. this._depthSortedIndices = new Uint32Array(0);
  20275. }
  20276. return this;
  20277. };
  20278. /**
  20279. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  20280. * Returns the mesh.
  20281. */
  20282. AbstractMesh.prototype.updateIndices = function (indices) {
  20283. return this;
  20284. };
  20285. /**
  20286. * The mesh Geometry. Actually used by the Mesh object.
  20287. * Returns a blank geometry object.
  20288. */
  20289. /**
  20290. * Creates new normals data for the mesh.
  20291. * @param updatable.
  20292. */
  20293. AbstractMesh.prototype.createNormals = function (updatable) {
  20294. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20295. var indices = this.getIndices();
  20296. var normals;
  20297. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20298. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20299. }
  20300. else {
  20301. normals = [];
  20302. }
  20303. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  20304. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  20305. };
  20306. /**
  20307. * Align the mesh with a normal.
  20308. * Returns the mesh.
  20309. */
  20310. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  20311. if (!upDirection) {
  20312. upDirection = BABYLON.Axis.Y;
  20313. }
  20314. var axisX = BABYLON.Tmp.Vector3[0];
  20315. var axisZ = BABYLON.Tmp.Vector3[1];
  20316. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  20317. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  20318. if (this.rotationQuaternion) {
  20319. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  20320. }
  20321. else {
  20322. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  20323. }
  20324. return this;
  20325. };
  20326. AbstractMesh.prototype.checkOcclusionQuery = function () {
  20327. var engine = this.getEngine();
  20328. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  20329. this._isOccluded = false;
  20330. return;
  20331. }
  20332. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  20333. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  20334. if (isOcclusionQueryAvailable) {
  20335. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  20336. this._isOcclusionQueryInProgress = false;
  20337. this._occlusionInternalRetryCounter = 0;
  20338. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  20339. }
  20340. else {
  20341. this._occlusionInternalRetryCounter++;
  20342. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  20343. this._isOcclusionQueryInProgress = false;
  20344. this._occlusionInternalRetryCounter = 0;
  20345. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  20346. // if strict continue the last state of the object.
  20347. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  20348. }
  20349. else {
  20350. return;
  20351. }
  20352. }
  20353. }
  20354. var scene = this.getScene();
  20355. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  20356. if (!this._occlusionQuery) {
  20357. this._occlusionQuery = engine.createQuery();
  20358. }
  20359. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  20360. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  20361. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  20362. this._isOcclusionQueryInProgress = true;
  20363. };
  20364. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  20365. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  20366. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  20367. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  20368. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  20369. return AbstractMesh;
  20370. }(BABYLON.TransformNode));
  20371. BABYLON.AbstractMesh = AbstractMesh;
  20372. })(BABYLON || (BABYLON = {}));
  20373. //# sourceMappingURL=babylon.abstractMesh.js.map
  20374. "use strict";
  20375. var BABYLON;
  20376. (function (BABYLON) {
  20377. /**
  20378. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  20379. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  20380. * 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.
  20381. */
  20382. var Light = /** @class */ (function (_super) {
  20383. __extends(Light, _super);
  20384. /**
  20385. * Creates a Light object in the scene.
  20386. * Documentation : http://doc.babylonjs.com/tutorials/lights
  20387. * @param name The firendly name of the light
  20388. * @param scene The scene the light belongs too
  20389. */
  20390. function Light(name, scene) {
  20391. var _this = _super.call(this, name, scene) || this;
  20392. /**
  20393. * Diffuse gives the basic color to an object.
  20394. */
  20395. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  20396. /**
  20397. * Specular produces a highlight color on an object.
  20398. * Note: This is note affecting PBR materials.
  20399. */
  20400. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  20401. /**
  20402. * Strength of the light.
  20403. * Note: By default it is define in the framework own unit.
  20404. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  20405. */
  20406. _this.intensity = 1.0;
  20407. /**
  20408. * Defines how far from the source the light is impacting in scene units.
  20409. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  20410. */
  20411. _this.range = Number.MAX_VALUE;
  20412. /**
  20413. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  20414. * of light.
  20415. */
  20416. _this._photometricScale = 1.0;
  20417. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  20418. _this._radius = 0.00001;
  20419. /**
  20420. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  20421. * exceeding the number allowed of the materials.
  20422. */
  20423. _this.renderPriority = 0;
  20424. /**
  20425. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  20426. * the current shadow generator.
  20427. */
  20428. _this.shadowEnabled = true;
  20429. _this._excludeWithLayerMask = 0;
  20430. _this._includeOnlyWithLayerMask = 0;
  20431. _this._lightmapMode = 0;
  20432. /**
  20433. * @ignore Internal use only.
  20434. */
  20435. _this._excludedMeshesIds = new Array();
  20436. /**
  20437. * @ignore Internal use only.
  20438. */
  20439. _this._includedOnlyMeshesIds = new Array();
  20440. _this.getScene().addLight(_this);
  20441. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  20442. _this._buildUniformLayout();
  20443. _this.includedOnlyMeshes = new Array();
  20444. _this.excludedMeshes = new Array();
  20445. _this._resyncMeshes();
  20446. return _this;
  20447. }
  20448. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  20449. /**
  20450. * If every light affecting the material is in this lightmapMode,
  20451. * material.lightmapTexture adds or multiplies
  20452. * (depends on material.useLightmapAsShadowmap)
  20453. * after every other light calculations.
  20454. */
  20455. get: function () {
  20456. return Light._LIGHTMAP_DEFAULT;
  20457. },
  20458. enumerable: true,
  20459. configurable: true
  20460. });
  20461. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  20462. /**
  20463. * material.lightmapTexture as only diffuse lighting from this light
  20464. * adds only specular lighting from this light
  20465. * adds dynamic shadows
  20466. */
  20467. get: function () {
  20468. return Light._LIGHTMAP_SPECULAR;
  20469. },
  20470. enumerable: true,
  20471. configurable: true
  20472. });
  20473. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  20474. /**
  20475. * material.lightmapTexture as only lighting
  20476. * no light calculation from this light
  20477. * only adds dynamic shadows from this light
  20478. */
  20479. get: function () {
  20480. return Light._LIGHTMAP_SHADOWSONLY;
  20481. },
  20482. enumerable: true,
  20483. configurable: true
  20484. });
  20485. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  20486. /**
  20487. * Each light type uses the default quantity according to its type:
  20488. * point/spot lights use luminous intensity
  20489. * directional lights use illuminance
  20490. */
  20491. get: function () {
  20492. return Light._INTENSITYMODE_AUTOMATIC;
  20493. },
  20494. enumerable: true,
  20495. configurable: true
  20496. });
  20497. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  20498. /**
  20499. * lumen (lm)
  20500. */
  20501. get: function () {
  20502. return Light._INTENSITYMODE_LUMINOUSPOWER;
  20503. },
  20504. enumerable: true,
  20505. configurable: true
  20506. });
  20507. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  20508. /**
  20509. * candela (lm/sr)
  20510. */
  20511. get: function () {
  20512. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  20513. },
  20514. enumerable: true,
  20515. configurable: true
  20516. });
  20517. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  20518. /**
  20519. * lux (lm/m^2)
  20520. */
  20521. get: function () {
  20522. return Light._INTENSITYMODE_ILLUMINANCE;
  20523. },
  20524. enumerable: true,
  20525. configurable: true
  20526. });
  20527. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  20528. /**
  20529. * nit (cd/m^2)
  20530. */
  20531. get: function () {
  20532. return Light._INTENSITYMODE_LUMINANCE;
  20533. },
  20534. enumerable: true,
  20535. configurable: true
  20536. });
  20537. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  20538. /**
  20539. * Light type const id of the point light.
  20540. */
  20541. get: function () {
  20542. return Light._LIGHTTYPEID_POINTLIGHT;
  20543. },
  20544. enumerable: true,
  20545. configurable: true
  20546. });
  20547. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  20548. /**
  20549. * Light type const id of the directional light.
  20550. */
  20551. get: function () {
  20552. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  20553. },
  20554. enumerable: true,
  20555. configurable: true
  20556. });
  20557. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  20558. /**
  20559. * Light type const id of the spot light.
  20560. */
  20561. get: function () {
  20562. return Light._LIGHTTYPEID_SPOTLIGHT;
  20563. },
  20564. enumerable: true,
  20565. configurable: true
  20566. });
  20567. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  20568. /**
  20569. * Light type const id of the hemispheric light.
  20570. */
  20571. get: function () {
  20572. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  20573. },
  20574. enumerable: true,
  20575. configurable: true
  20576. });
  20577. Object.defineProperty(Light.prototype, "intensityMode", {
  20578. /**
  20579. * Gets the photometric scale used to interpret the intensity.
  20580. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  20581. */
  20582. get: function () {
  20583. return this._intensityMode;
  20584. },
  20585. /**
  20586. * Sets the photometric scale used to interpret the intensity.
  20587. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  20588. */
  20589. set: function (value) {
  20590. this._intensityMode = value;
  20591. this._computePhotometricScale();
  20592. },
  20593. enumerable: true,
  20594. configurable: true
  20595. });
  20596. ;
  20597. ;
  20598. Object.defineProperty(Light.prototype, "radius", {
  20599. /**
  20600. * Gets the light radius used by PBR Materials to simulate soft area lights.
  20601. */
  20602. get: function () {
  20603. return this._radius;
  20604. },
  20605. /**
  20606. * sets the light radius used by PBR Materials to simulate soft area lights.
  20607. */
  20608. set: function (value) {
  20609. this._radius = value;
  20610. this._computePhotometricScale();
  20611. },
  20612. enumerable: true,
  20613. configurable: true
  20614. });
  20615. ;
  20616. ;
  20617. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  20618. /**
  20619. * Gets the only meshes impacted by this light.
  20620. */
  20621. get: function () {
  20622. return this._includedOnlyMeshes;
  20623. },
  20624. /**
  20625. * Sets the only meshes impacted by this light.
  20626. */
  20627. set: function (value) {
  20628. this._includedOnlyMeshes = value;
  20629. this._hookArrayForIncludedOnly(value);
  20630. },
  20631. enumerable: true,
  20632. configurable: true
  20633. });
  20634. Object.defineProperty(Light.prototype, "excludedMeshes", {
  20635. /**
  20636. * Gets the meshes not impacted by this light.
  20637. */
  20638. get: function () {
  20639. return this._excludedMeshes;
  20640. },
  20641. /**
  20642. * Sets the meshes not impacted by this light.
  20643. */
  20644. set: function (value) {
  20645. this._excludedMeshes = value;
  20646. this._hookArrayForExcluded(value);
  20647. },
  20648. enumerable: true,
  20649. configurable: true
  20650. });
  20651. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  20652. /**
  20653. * Gets the layer id use to find what meshes are not impacted by the light.
  20654. * Inactive if 0
  20655. */
  20656. get: function () {
  20657. return this._excludeWithLayerMask;
  20658. },
  20659. /**
  20660. * Sets the layer id use to find what meshes are not impacted by the light.
  20661. * Inactive if 0
  20662. */
  20663. set: function (value) {
  20664. this._excludeWithLayerMask = value;
  20665. this._resyncMeshes();
  20666. },
  20667. enumerable: true,
  20668. configurable: true
  20669. });
  20670. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  20671. /**
  20672. * Gets the layer id use to find what meshes are impacted by the light.
  20673. * Inactive if 0
  20674. */
  20675. get: function () {
  20676. return this._includeOnlyWithLayerMask;
  20677. },
  20678. /**
  20679. * Sets the layer id use to find what meshes are impacted by the light.
  20680. * Inactive if 0
  20681. */
  20682. set: function (value) {
  20683. this._includeOnlyWithLayerMask = value;
  20684. this._resyncMeshes();
  20685. },
  20686. enumerable: true,
  20687. configurable: true
  20688. });
  20689. Object.defineProperty(Light.prototype, "lightmapMode", {
  20690. /**
  20691. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  20692. */
  20693. get: function () {
  20694. return this._lightmapMode;
  20695. },
  20696. /**
  20697. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  20698. */
  20699. set: function (value) {
  20700. if (this._lightmapMode === value) {
  20701. return;
  20702. }
  20703. this._lightmapMode = value;
  20704. this._markMeshesAsLightDirty();
  20705. },
  20706. enumerable: true,
  20707. configurable: true
  20708. });
  20709. /**
  20710. * Returns the string "Light".
  20711. * @returns the class name
  20712. */
  20713. Light.prototype.getClassName = function () {
  20714. return "Light";
  20715. };
  20716. /**
  20717. * Converts the light information to a readable string for debug purpose.
  20718. * @param fullDetails Supports for multiple levels of logging within scene loading
  20719. * @returns the human readable light info
  20720. */
  20721. Light.prototype.toString = function (fullDetails) {
  20722. var ret = "Name: " + this.name;
  20723. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  20724. if (this.animations) {
  20725. for (var i = 0; i < this.animations.length; i++) {
  20726. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  20727. }
  20728. }
  20729. if (fullDetails) {
  20730. }
  20731. return ret;
  20732. };
  20733. /**
  20734. * Set the enabled state of this node.
  20735. * @param value - the new enabled state
  20736. */
  20737. Light.prototype.setEnabled = function (value) {
  20738. _super.prototype.setEnabled.call(this, value);
  20739. this._resyncMeshes();
  20740. };
  20741. /**
  20742. * Returns the Light associated shadow generator if any.
  20743. * @return the associated shadow generator.
  20744. */
  20745. Light.prototype.getShadowGenerator = function () {
  20746. return this._shadowGenerator;
  20747. };
  20748. /**
  20749. * Returns a Vector3, the absolute light position in the World.
  20750. * @returns the world space position of the light
  20751. */
  20752. Light.prototype.getAbsolutePosition = function () {
  20753. return BABYLON.Vector3.Zero();
  20754. };
  20755. /**
  20756. * Specifies if the light will affect the passed mesh.
  20757. * @param mesh The mesh to test against the light
  20758. * @return true the mesh is affected otherwise, false.
  20759. */
  20760. Light.prototype.canAffectMesh = function (mesh) {
  20761. if (!mesh) {
  20762. return true;
  20763. }
  20764. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  20765. return false;
  20766. }
  20767. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  20768. return false;
  20769. }
  20770. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  20771. return false;
  20772. }
  20773. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  20774. return false;
  20775. }
  20776. return true;
  20777. };
  20778. /**
  20779. * Computes and Returns the light World matrix.
  20780. * @returns the world matrix
  20781. */
  20782. Light.prototype.getWorldMatrix = function () {
  20783. this._currentRenderId = this.getScene().getRenderId();
  20784. this._childRenderId = this._currentRenderId;
  20785. var worldMatrix = this._getWorldMatrix();
  20786. if (this.parent && this.parent.getWorldMatrix) {
  20787. if (!this._parentedWorldMatrix) {
  20788. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  20789. }
  20790. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  20791. this._markSyncedWithParent();
  20792. return this._parentedWorldMatrix;
  20793. }
  20794. return worldMatrix;
  20795. };
  20796. /**
  20797. * Sort function to order lights for rendering.
  20798. * @param a First Light object to compare to second.
  20799. * @param b Second Light object to compare first.
  20800. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  20801. */
  20802. Light.CompareLightsPriority = function (a, b) {
  20803. //shadow-casting lights have priority over non-shadow-casting lights
  20804. //the renderPrioirty is a secondary sort criterion
  20805. if (a.shadowEnabled !== b.shadowEnabled) {
  20806. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  20807. }
  20808. return b.renderPriority - a.renderPriority;
  20809. };
  20810. /**
  20811. * Releases resources associated with this node.
  20812. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20813. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20814. */
  20815. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20816. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20817. if (this._shadowGenerator) {
  20818. this._shadowGenerator.dispose();
  20819. this._shadowGenerator = null;
  20820. }
  20821. // Animations
  20822. this.getScene().stopAnimation(this);
  20823. // Remove from meshes
  20824. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  20825. var mesh = _a[_i];
  20826. mesh._removeLightSource(this);
  20827. }
  20828. this._uniformBuffer.dispose();
  20829. // Remove from scene
  20830. this.getScene().removeLight(this);
  20831. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20832. };
  20833. /**
  20834. * Returns the light type ID (integer).
  20835. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  20836. */
  20837. Light.prototype.getTypeID = function () {
  20838. return 0;
  20839. };
  20840. /**
  20841. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  20842. * @returns the scaled intensity in intensity mode unit
  20843. */
  20844. Light.prototype.getScaledIntensity = function () {
  20845. return this._photometricScale * this.intensity;
  20846. };
  20847. /**
  20848. * Returns a new Light object, named "name", from the current one.
  20849. * @param name The name of the cloned light
  20850. * @returns the new created light
  20851. */
  20852. Light.prototype.clone = function (name) {
  20853. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  20854. if (!constructor) {
  20855. return null;
  20856. }
  20857. return BABYLON.SerializationHelper.Clone(constructor, this);
  20858. };
  20859. /**
  20860. * Serializes the current light into a Serialization object.
  20861. * @returns the serialized object.
  20862. */
  20863. Light.prototype.serialize = function () {
  20864. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20865. // Type
  20866. serializationObject.type = this.getTypeID();
  20867. // Parent
  20868. if (this.parent) {
  20869. serializationObject.parentId = this.parent.id;
  20870. }
  20871. // Inclusion / exclusions
  20872. if (this.excludedMeshes.length > 0) {
  20873. serializationObject.excludedMeshesIds = [];
  20874. this.excludedMeshes.forEach(function (mesh) {
  20875. serializationObject.excludedMeshesIds.push(mesh.id);
  20876. });
  20877. }
  20878. if (this.includedOnlyMeshes.length > 0) {
  20879. serializationObject.includedOnlyMeshesIds = [];
  20880. this.includedOnlyMeshes.forEach(function (mesh) {
  20881. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  20882. });
  20883. }
  20884. // Animations
  20885. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20886. serializationObject.ranges = this.serializeAnimationRanges();
  20887. return serializationObject;
  20888. };
  20889. /**
  20890. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  20891. * This new light is named "name" and added to the passed scene.
  20892. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  20893. * @param name The friendly name of the light
  20894. * @param scene The scene the new light will belong to
  20895. * @returns the constructor function
  20896. */
  20897. Light.GetConstructorFromName = function (type, name, scene) {
  20898. switch (type) {
  20899. case 0:
  20900. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  20901. case 1:
  20902. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  20903. case 2:
  20904. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  20905. case 3:
  20906. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  20907. }
  20908. return null;
  20909. };
  20910. /**
  20911. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  20912. * @param parsedLight The JSON representation of the light
  20913. * @param scene The scene to create the parsed light in
  20914. * @returns the created light after parsing
  20915. */
  20916. Light.Parse = function (parsedLight, scene) {
  20917. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  20918. if (!constructor) {
  20919. return null;
  20920. }
  20921. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  20922. // Inclusion / exclusions
  20923. if (parsedLight.excludedMeshesIds) {
  20924. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  20925. }
  20926. if (parsedLight.includedOnlyMeshesIds) {
  20927. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  20928. }
  20929. // Parent
  20930. if (parsedLight.parentId) {
  20931. light._waitingParentId = parsedLight.parentId;
  20932. }
  20933. // Animations
  20934. if (parsedLight.animations) {
  20935. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  20936. var parsedAnimation = parsedLight.animations[animationIndex];
  20937. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20938. }
  20939. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  20940. }
  20941. if (parsedLight.autoAnimate) {
  20942. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  20943. }
  20944. return light;
  20945. };
  20946. Light.prototype._hookArrayForExcluded = function (array) {
  20947. var _this = this;
  20948. var oldPush = array.push;
  20949. array.push = function () {
  20950. var items = [];
  20951. for (var _i = 0; _i < arguments.length; _i++) {
  20952. items[_i] = arguments[_i];
  20953. }
  20954. var result = oldPush.apply(array, items);
  20955. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  20956. var item = items_1[_a];
  20957. item._resyncLighSource(_this);
  20958. }
  20959. return result;
  20960. };
  20961. var oldSplice = array.splice;
  20962. array.splice = function (index, deleteCount) {
  20963. var deleted = oldSplice.apply(array, [index, deleteCount]);
  20964. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  20965. var item = deleted_1[_i];
  20966. item._resyncLighSource(_this);
  20967. }
  20968. return deleted;
  20969. };
  20970. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  20971. var item = array_1[_i];
  20972. item._resyncLighSource(this);
  20973. }
  20974. };
  20975. Light.prototype._hookArrayForIncludedOnly = function (array) {
  20976. var _this = this;
  20977. var oldPush = array.push;
  20978. array.push = function () {
  20979. var items = [];
  20980. for (var _i = 0; _i < arguments.length; _i++) {
  20981. items[_i] = arguments[_i];
  20982. }
  20983. var result = oldPush.apply(array, items);
  20984. _this._resyncMeshes();
  20985. return result;
  20986. };
  20987. var oldSplice = array.splice;
  20988. array.splice = function (index, deleteCount) {
  20989. var deleted = oldSplice.apply(array, [index, deleteCount]);
  20990. _this._resyncMeshes();
  20991. return deleted;
  20992. };
  20993. this._resyncMeshes();
  20994. };
  20995. Light.prototype._resyncMeshes = function () {
  20996. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  20997. var mesh = _a[_i];
  20998. mesh._resyncLighSource(this);
  20999. }
  21000. };
  21001. /**
  21002. * Forces the meshes to update their light related information in their rendering used effects
  21003. * @ignore Internal Use Only
  21004. */
  21005. Light.prototype._markMeshesAsLightDirty = function () {
  21006. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21007. var mesh = _a[_i];
  21008. if (mesh._lightSources.indexOf(this) !== -1) {
  21009. mesh._markSubMeshesAsLightDirty();
  21010. }
  21011. }
  21012. };
  21013. /**
  21014. * Recomputes the cached photometric scale if needed.
  21015. */
  21016. Light.prototype._computePhotometricScale = function () {
  21017. this._photometricScale = this._getPhotometricScale();
  21018. this.getScene().resetCachedMaterial();
  21019. };
  21020. /**
  21021. * Returns the Photometric Scale according to the light type and intensity mode.
  21022. */
  21023. Light.prototype._getPhotometricScale = function () {
  21024. var photometricScale = 0.0;
  21025. var lightTypeID = this.getTypeID();
  21026. //get photometric mode
  21027. var photometricMode = this.intensityMode;
  21028. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21029. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21030. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21031. }
  21032. else {
  21033. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21034. }
  21035. }
  21036. //compute photometric scale
  21037. switch (lightTypeID) {
  21038. case Light.LIGHTTYPEID_POINTLIGHT:
  21039. case Light.LIGHTTYPEID_SPOTLIGHT:
  21040. switch (photometricMode) {
  21041. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21042. photometricScale = 1.0 / (4.0 * Math.PI);
  21043. break;
  21044. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21045. photometricScale = 1.0;
  21046. break;
  21047. case Light.INTENSITYMODE_LUMINANCE:
  21048. photometricScale = this.radius * this.radius;
  21049. break;
  21050. }
  21051. break;
  21052. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21053. switch (photometricMode) {
  21054. case Light.INTENSITYMODE_ILLUMINANCE:
  21055. photometricScale = 1.0;
  21056. break;
  21057. case Light.INTENSITYMODE_LUMINANCE:
  21058. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  21059. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  21060. var apexAngleRadians = this.radius;
  21061. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  21062. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  21063. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  21064. photometricScale = solidAngle;
  21065. break;
  21066. }
  21067. break;
  21068. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  21069. // No fall off in hemisperic light.
  21070. photometricScale = 1.0;
  21071. break;
  21072. }
  21073. return photometricScale;
  21074. };
  21075. /**
  21076. * Reorder the light in the scene according to their defined priority.
  21077. * @ignore Internal Use Only
  21078. */
  21079. Light.prototype._reorderLightsInScene = function () {
  21080. var scene = this.getScene();
  21081. if (this._renderPriority != 0) {
  21082. scene.requireLightSorting = true;
  21083. }
  21084. this.getScene().sortLightsByPriority();
  21085. };
  21086. //lightmapMode Consts
  21087. Light._LIGHTMAP_DEFAULT = 0;
  21088. Light._LIGHTMAP_SPECULAR = 1;
  21089. Light._LIGHTMAP_SHADOWSONLY = 2;
  21090. // Intensity Mode Consts
  21091. Light._INTENSITYMODE_AUTOMATIC = 0;
  21092. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  21093. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  21094. Light._INTENSITYMODE_ILLUMINANCE = 3;
  21095. Light._INTENSITYMODE_LUMINANCE = 4;
  21096. // Light types ids const.
  21097. Light._LIGHTTYPEID_POINTLIGHT = 0;
  21098. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  21099. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  21100. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  21101. __decorate([
  21102. BABYLON.serializeAsColor3()
  21103. ], Light.prototype, "diffuse", void 0);
  21104. __decorate([
  21105. BABYLON.serializeAsColor3()
  21106. ], Light.prototype, "specular", void 0);
  21107. __decorate([
  21108. BABYLON.serialize()
  21109. ], Light.prototype, "intensity", void 0);
  21110. __decorate([
  21111. BABYLON.serialize()
  21112. ], Light.prototype, "range", void 0);
  21113. __decorate([
  21114. BABYLON.serialize()
  21115. ], Light.prototype, "intensityMode", null);
  21116. __decorate([
  21117. BABYLON.serialize()
  21118. ], Light.prototype, "radius", null);
  21119. __decorate([
  21120. BABYLON.serialize()
  21121. ], Light.prototype, "_renderPriority", void 0);
  21122. __decorate([
  21123. BABYLON.expandToProperty("_reorderLightsInScene")
  21124. ], Light.prototype, "renderPriority", void 0);
  21125. __decorate([
  21126. BABYLON.serialize()
  21127. ], Light.prototype, "shadowEnabled", void 0);
  21128. __decorate([
  21129. BABYLON.serialize("excludeWithLayerMask")
  21130. ], Light.prototype, "_excludeWithLayerMask", void 0);
  21131. __decorate([
  21132. BABYLON.serialize("includeOnlyWithLayerMask")
  21133. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  21134. __decorate([
  21135. BABYLON.serialize("lightmapMode")
  21136. ], Light.prototype, "_lightmapMode", void 0);
  21137. return Light;
  21138. }(BABYLON.Node));
  21139. BABYLON.Light = Light;
  21140. })(BABYLON || (BABYLON = {}));
  21141. //# sourceMappingURL=babylon.light.js.map
  21142. "use strict";
  21143. var BABYLON;
  21144. (function (BABYLON) {
  21145. var Camera = /** @class */ (function (_super) {
  21146. __extends(Camera, _super);
  21147. function Camera(name, position, scene) {
  21148. var _this = _super.call(this, name, scene) || this;
  21149. /**
  21150. * The vector the camera should consider as up.
  21151. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  21152. */
  21153. _this.upVector = BABYLON.Vector3.Up();
  21154. _this.orthoLeft = null;
  21155. _this.orthoRight = null;
  21156. _this.orthoBottom = null;
  21157. _this.orthoTop = null;
  21158. /**
  21159. * FOV is set in Radians. (default is 0.8)
  21160. */
  21161. _this.fov = 0.8;
  21162. _this.minZ = 1;
  21163. _this.maxZ = 10000.0;
  21164. _this.inertia = 0.9;
  21165. _this.mode = Camera.PERSPECTIVE_CAMERA;
  21166. _this.isIntermediate = false;
  21167. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  21168. /**
  21169. * Restricts the camera to viewing objects with the same layerMask.
  21170. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  21171. */
  21172. _this.layerMask = 0x0FFFFFFF;
  21173. /**
  21174. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  21175. */
  21176. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  21177. // Camera rig members
  21178. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  21179. _this._rigCameras = new Array();
  21180. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  21181. _this._skipRendering = false;
  21182. _this.customRenderTargets = new Array();
  21183. // Observables
  21184. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  21185. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  21186. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  21187. _this.onRestoreStateObservable = new BABYLON.Observable();
  21188. // Cache
  21189. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  21190. _this._projectionMatrix = new BABYLON.Matrix();
  21191. _this._doNotComputeProjectionMatrix = false;
  21192. _this._postProcesses = new Array();
  21193. _this._transformMatrix = BABYLON.Matrix.Zero();
  21194. _this._activeMeshes = new BABYLON.SmartArray(256);
  21195. _this._globalPosition = BABYLON.Vector3.Zero();
  21196. _this._refreshFrustumPlanes = true;
  21197. _this.getScene().addCamera(_this);
  21198. if (!_this.getScene().activeCamera) {
  21199. _this.getScene().activeCamera = _this;
  21200. }
  21201. _this.position = position;
  21202. return _this;
  21203. }
  21204. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  21205. get: function () {
  21206. return Camera._PERSPECTIVE_CAMERA;
  21207. },
  21208. enumerable: true,
  21209. configurable: true
  21210. });
  21211. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  21212. get: function () {
  21213. return Camera._ORTHOGRAPHIC_CAMERA;
  21214. },
  21215. enumerable: true,
  21216. configurable: true
  21217. });
  21218. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  21219. /**
  21220. * This is the default FOV mode for perspective cameras.
  21221. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  21222. *
  21223. */
  21224. get: function () {
  21225. return Camera._FOVMODE_VERTICAL_FIXED;
  21226. },
  21227. enumerable: true,
  21228. configurable: true
  21229. });
  21230. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  21231. /**
  21232. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  21233. *
  21234. */
  21235. get: function () {
  21236. return Camera._FOVMODE_HORIZONTAL_FIXED;
  21237. },
  21238. enumerable: true,
  21239. configurable: true
  21240. });
  21241. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  21242. get: function () {
  21243. return Camera._RIG_MODE_NONE;
  21244. },
  21245. enumerable: true,
  21246. configurable: true
  21247. });
  21248. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  21249. get: function () {
  21250. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  21251. },
  21252. enumerable: true,
  21253. configurable: true
  21254. });
  21255. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  21256. get: function () {
  21257. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  21258. },
  21259. enumerable: true,
  21260. configurable: true
  21261. });
  21262. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  21263. get: function () {
  21264. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  21265. },
  21266. enumerable: true,
  21267. configurable: true
  21268. });
  21269. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  21270. get: function () {
  21271. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  21272. },
  21273. enumerable: true,
  21274. configurable: true
  21275. });
  21276. Object.defineProperty(Camera, "RIG_MODE_VR", {
  21277. get: function () {
  21278. return Camera._RIG_MODE_VR;
  21279. },
  21280. enumerable: true,
  21281. configurable: true
  21282. });
  21283. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  21284. get: function () {
  21285. return Camera._RIG_MODE_WEBVR;
  21286. },
  21287. enumerable: true,
  21288. configurable: true
  21289. });
  21290. /**
  21291. * Store current camera state (fov, position, etc..)
  21292. */
  21293. Camera.prototype.storeState = function () {
  21294. this._stateStored = true;
  21295. this._storedFov = this.fov;
  21296. return this;
  21297. };
  21298. /**
  21299. * Restores the camera state values if it has been stored. You must call storeState() first
  21300. */
  21301. Camera.prototype._restoreStateValues = function () {
  21302. if (!this._stateStored) {
  21303. return false;
  21304. }
  21305. this.fov = this._storedFov;
  21306. return true;
  21307. };
  21308. /**
  21309. * Restored camera state. You must call storeState() first
  21310. */
  21311. Camera.prototype.restoreState = function () {
  21312. if (this._restoreStateValues()) {
  21313. this.onRestoreStateObservable.notifyObservers(this);
  21314. return true;
  21315. }
  21316. return false;
  21317. };
  21318. Camera.prototype.getClassName = function () {
  21319. return "Camera";
  21320. };
  21321. /**
  21322. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  21323. */
  21324. Camera.prototype.toString = function (fullDetails) {
  21325. var ret = "Name: " + this.name;
  21326. ret += ", type: " + this.getClassName();
  21327. if (this.animations) {
  21328. for (var i = 0; i < this.animations.length; i++) {
  21329. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21330. }
  21331. }
  21332. if (fullDetails) {
  21333. }
  21334. return ret;
  21335. };
  21336. Object.defineProperty(Camera.prototype, "globalPosition", {
  21337. get: function () {
  21338. return this._globalPosition;
  21339. },
  21340. enumerable: true,
  21341. configurable: true
  21342. });
  21343. Camera.prototype.getActiveMeshes = function () {
  21344. return this._activeMeshes;
  21345. };
  21346. Camera.prototype.isActiveMesh = function (mesh) {
  21347. return (this._activeMeshes.indexOf(mesh) !== -1);
  21348. };
  21349. /**
  21350. * Is this camera ready to be used/rendered
  21351. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  21352. * @return true if the camera is ready
  21353. */
  21354. Camera.prototype.isReady = function (completeCheck) {
  21355. if (completeCheck === void 0) { completeCheck = false; }
  21356. if (completeCheck) {
  21357. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  21358. var pp = _a[_i];
  21359. if (pp && !pp.isReady()) {
  21360. return false;
  21361. }
  21362. }
  21363. }
  21364. return _super.prototype.isReady.call(this, completeCheck);
  21365. };
  21366. //Cache
  21367. Camera.prototype._initCache = function () {
  21368. _super.prototype._initCache.call(this);
  21369. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21370. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21371. this._cache.mode = undefined;
  21372. this._cache.minZ = undefined;
  21373. this._cache.maxZ = undefined;
  21374. this._cache.fov = undefined;
  21375. this._cache.fovMode = undefined;
  21376. this._cache.aspectRatio = undefined;
  21377. this._cache.orthoLeft = undefined;
  21378. this._cache.orthoRight = undefined;
  21379. this._cache.orthoBottom = undefined;
  21380. this._cache.orthoTop = undefined;
  21381. this._cache.renderWidth = undefined;
  21382. this._cache.renderHeight = undefined;
  21383. };
  21384. Camera.prototype._updateCache = function (ignoreParentClass) {
  21385. if (!ignoreParentClass) {
  21386. _super.prototype._updateCache.call(this);
  21387. }
  21388. this._cache.position.copyFrom(this.position);
  21389. this._cache.upVector.copyFrom(this.upVector);
  21390. };
  21391. // Synchronized
  21392. Camera.prototype._isSynchronized = function () {
  21393. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  21394. };
  21395. Camera.prototype._isSynchronizedViewMatrix = function () {
  21396. if (!_super.prototype._isSynchronized.call(this))
  21397. return false;
  21398. return this._cache.position.equals(this.position)
  21399. && this._cache.upVector.equals(this.upVector)
  21400. && this.isSynchronizedWithParent();
  21401. };
  21402. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  21403. var check = this._cache.mode === this.mode
  21404. && this._cache.minZ === this.minZ
  21405. && this._cache.maxZ === this.maxZ;
  21406. if (!check) {
  21407. return false;
  21408. }
  21409. var engine = this.getEngine();
  21410. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  21411. check = this._cache.fov === this.fov
  21412. && this._cache.fovMode === this.fovMode
  21413. && this._cache.aspectRatio === engine.getAspectRatio(this);
  21414. }
  21415. else {
  21416. check = this._cache.orthoLeft === this.orthoLeft
  21417. && this._cache.orthoRight === this.orthoRight
  21418. && this._cache.orthoBottom === this.orthoBottom
  21419. && this._cache.orthoTop === this.orthoTop
  21420. && this._cache.renderWidth === engine.getRenderWidth()
  21421. && this._cache.renderHeight === engine.getRenderHeight();
  21422. }
  21423. return check;
  21424. };
  21425. // Controls
  21426. Camera.prototype.attachControl = function (element, noPreventDefault) {
  21427. };
  21428. Camera.prototype.detachControl = function (element) {
  21429. };
  21430. Camera.prototype.update = function () {
  21431. this._checkInputs();
  21432. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  21433. this._updateRigCameras();
  21434. }
  21435. };
  21436. Camera.prototype._checkInputs = function () {
  21437. this.onAfterCheckInputsObservable.notifyObservers(this);
  21438. };
  21439. Object.defineProperty(Camera.prototype, "rigCameras", {
  21440. get: function () {
  21441. return this._rigCameras;
  21442. },
  21443. enumerable: true,
  21444. configurable: true
  21445. });
  21446. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  21447. get: function () {
  21448. return this._rigPostProcess;
  21449. },
  21450. enumerable: true,
  21451. configurable: true
  21452. });
  21453. /**
  21454. * Internal, gets the first post proces.
  21455. * @returns the first post process to be run on this camera.
  21456. */
  21457. Camera.prototype._getFirstPostProcess = function () {
  21458. for (var pp in this._postProcesses) {
  21459. if (this._postProcesses[pp] !== null) {
  21460. return this._postProcesses[pp];
  21461. }
  21462. }
  21463. return null;
  21464. };
  21465. Camera.prototype._cascadePostProcessesToRigCams = function () {
  21466. // invalidate framebuffer
  21467. var firstPostProcess = this._getFirstPostProcess();
  21468. if (firstPostProcess) {
  21469. firstPostProcess.markTextureDirty();
  21470. }
  21471. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  21472. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  21473. var cam = this._rigCameras[i];
  21474. var rigPostProcess = cam._rigPostProcess;
  21475. // for VR rig, there does not have to be a post process
  21476. if (rigPostProcess) {
  21477. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  21478. if (isPass) {
  21479. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  21480. cam.isIntermediate = this._postProcesses.length === 0;
  21481. }
  21482. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  21483. rigPostProcess.markTextureDirty();
  21484. }
  21485. else {
  21486. cam._postProcesses = this._postProcesses.slice(0);
  21487. }
  21488. }
  21489. };
  21490. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  21491. if (insertAt === void 0) { insertAt = null; }
  21492. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  21493. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  21494. return 0;
  21495. }
  21496. if (insertAt == null || insertAt < 0) {
  21497. this._postProcesses.push(postProcess);
  21498. }
  21499. else if (this._postProcesses[insertAt] === null) {
  21500. this._postProcesses[insertAt] = postProcess;
  21501. }
  21502. else {
  21503. this._postProcesses.splice(insertAt, 0, postProcess);
  21504. }
  21505. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  21506. return this._postProcesses.indexOf(postProcess);
  21507. };
  21508. Camera.prototype.detachPostProcess = function (postProcess) {
  21509. var idx = this._postProcesses.indexOf(postProcess);
  21510. if (idx !== -1) {
  21511. this._postProcesses[idx] = null;
  21512. }
  21513. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  21514. };
  21515. Camera.prototype.getWorldMatrix = function () {
  21516. if (!this._worldMatrix) {
  21517. this._worldMatrix = BABYLON.Matrix.Identity();
  21518. }
  21519. var viewMatrix = this.getViewMatrix();
  21520. viewMatrix.invertToRef(this._worldMatrix);
  21521. return this._worldMatrix;
  21522. };
  21523. Camera.prototype._getViewMatrix = function () {
  21524. return BABYLON.Matrix.Identity();
  21525. };
  21526. Camera.prototype.getViewMatrix = function (force) {
  21527. if (!force && this._isSynchronizedViewMatrix()) {
  21528. return this._computedViewMatrix;
  21529. }
  21530. this.updateCache();
  21531. this._computedViewMatrix = this._getViewMatrix();
  21532. this._currentRenderId = this.getScene().getRenderId();
  21533. this._childRenderId = this._currentRenderId;
  21534. this._refreshFrustumPlanes = true;
  21535. if (!this.parent || !this.parent.getWorldMatrix) {
  21536. this._globalPosition.copyFrom(this.position);
  21537. }
  21538. else {
  21539. if (!this._worldMatrix) {
  21540. this._worldMatrix = BABYLON.Matrix.Identity();
  21541. }
  21542. this._computedViewMatrix.invertToRef(this._worldMatrix);
  21543. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  21544. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  21545. this._computedViewMatrix.invert();
  21546. this._markSyncedWithParent();
  21547. }
  21548. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  21549. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  21550. }
  21551. this.onViewMatrixChangedObservable.notifyObservers(this);
  21552. return this._computedViewMatrix;
  21553. };
  21554. Camera.prototype.freezeProjectionMatrix = function (projection) {
  21555. this._doNotComputeProjectionMatrix = true;
  21556. if (projection !== undefined) {
  21557. this._projectionMatrix = projection;
  21558. }
  21559. };
  21560. ;
  21561. Camera.prototype.unfreezeProjectionMatrix = function () {
  21562. this._doNotComputeProjectionMatrix = false;
  21563. };
  21564. ;
  21565. Camera.prototype.getProjectionMatrix = function (force) {
  21566. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  21567. return this._projectionMatrix;
  21568. }
  21569. // Cache
  21570. this._cache.mode = this.mode;
  21571. this._cache.minZ = this.minZ;
  21572. this._cache.maxZ = this.maxZ;
  21573. // Matrix
  21574. this._refreshFrustumPlanes = true;
  21575. var engine = this.getEngine();
  21576. var scene = this.getScene();
  21577. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  21578. this._cache.fov = this.fov;
  21579. this._cache.fovMode = this.fovMode;
  21580. this._cache.aspectRatio = engine.getAspectRatio(this);
  21581. if (this.minZ <= 0) {
  21582. this.minZ = 0.1;
  21583. }
  21584. if (scene.useRightHandedSystem) {
  21585. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  21586. }
  21587. else {
  21588. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  21589. }
  21590. }
  21591. else {
  21592. var halfWidth = engine.getRenderWidth() / 2.0;
  21593. var halfHeight = engine.getRenderHeight() / 2.0;
  21594. if (scene.useRightHandedSystem) {
  21595. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  21596. }
  21597. else {
  21598. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  21599. }
  21600. this._cache.orthoLeft = this.orthoLeft;
  21601. this._cache.orthoRight = this.orthoRight;
  21602. this._cache.orthoBottom = this.orthoBottom;
  21603. this._cache.orthoTop = this.orthoTop;
  21604. this._cache.renderWidth = engine.getRenderWidth();
  21605. this._cache.renderHeight = engine.getRenderHeight();
  21606. }
  21607. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  21608. return this._projectionMatrix;
  21609. };
  21610. Camera.prototype.getTranformationMatrix = function () {
  21611. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  21612. return this._transformMatrix;
  21613. };
  21614. Camera.prototype.updateFrustumPlanes = function () {
  21615. if (!this._refreshFrustumPlanes) {
  21616. return;
  21617. }
  21618. this.getTranformationMatrix();
  21619. if (!this._frustumPlanes) {
  21620. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  21621. }
  21622. else {
  21623. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  21624. }
  21625. this._refreshFrustumPlanes = false;
  21626. };
  21627. Camera.prototype.isInFrustum = function (target) {
  21628. this.updateFrustumPlanes();
  21629. return target.isInFrustum(this._frustumPlanes);
  21630. };
  21631. Camera.prototype.isCompletelyInFrustum = function (target) {
  21632. this.updateFrustumPlanes();
  21633. return target.isCompletelyInFrustum(this._frustumPlanes);
  21634. };
  21635. Camera.prototype.getForwardRay = function (length, transform, origin) {
  21636. if (length === void 0) { length = 100; }
  21637. if (!transform) {
  21638. transform = this.getWorldMatrix();
  21639. }
  21640. if (!origin) {
  21641. origin = this.position;
  21642. }
  21643. var forward = new BABYLON.Vector3(0, 0, 1);
  21644. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  21645. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  21646. return new BABYLON.Ray(origin, direction, length);
  21647. };
  21648. /**
  21649. * Releases resources associated with this node.
  21650. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21651. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21652. */
  21653. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21654. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21655. // Observables
  21656. this.onViewMatrixChangedObservable.clear();
  21657. this.onProjectionMatrixChangedObservable.clear();
  21658. this.onAfterCheckInputsObservable.clear();
  21659. this.onRestoreStateObservable.clear();
  21660. // Inputs
  21661. if (this.inputs) {
  21662. this.inputs.clear();
  21663. }
  21664. // Animations
  21665. this.getScene().stopAnimation(this);
  21666. // Remove from scene
  21667. this.getScene().removeCamera(this);
  21668. while (this._rigCameras.length > 0) {
  21669. var camera = this._rigCameras.pop();
  21670. if (camera) {
  21671. camera.dispose();
  21672. }
  21673. }
  21674. // Postprocesses
  21675. if (this._rigPostProcess) {
  21676. this._rigPostProcess.dispose(this);
  21677. this._rigPostProcess = null;
  21678. this._postProcesses = [];
  21679. }
  21680. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  21681. this._rigPostProcess = null;
  21682. this._postProcesses = [];
  21683. }
  21684. else {
  21685. var i = this._postProcesses.length;
  21686. while (--i >= 0) {
  21687. var postProcess = this._postProcesses[i];
  21688. if (postProcess) {
  21689. postProcess.dispose(this);
  21690. }
  21691. }
  21692. }
  21693. // Render targets
  21694. var i = this.customRenderTargets.length;
  21695. while (--i >= 0) {
  21696. this.customRenderTargets[i].dispose();
  21697. }
  21698. this.customRenderTargets = [];
  21699. // Active Meshes
  21700. this._activeMeshes.dispose();
  21701. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21702. };
  21703. Object.defineProperty(Camera.prototype, "leftCamera", {
  21704. // ---- Camera rigs section ----
  21705. get: function () {
  21706. if (this._rigCameras.length < 1) {
  21707. return null;
  21708. }
  21709. return this._rigCameras[0];
  21710. },
  21711. enumerable: true,
  21712. configurable: true
  21713. });
  21714. Object.defineProperty(Camera.prototype, "rightCamera", {
  21715. get: function () {
  21716. if (this._rigCameras.length < 2) {
  21717. return null;
  21718. }
  21719. return this._rigCameras[1];
  21720. },
  21721. enumerable: true,
  21722. configurable: true
  21723. });
  21724. Camera.prototype.getLeftTarget = function () {
  21725. if (this._rigCameras.length < 1) {
  21726. return null;
  21727. }
  21728. return this._rigCameras[0].getTarget();
  21729. };
  21730. Camera.prototype.getRightTarget = function () {
  21731. if (this._rigCameras.length < 2) {
  21732. return null;
  21733. }
  21734. return this._rigCameras[1].getTarget();
  21735. };
  21736. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  21737. if (this.cameraRigMode === mode) {
  21738. return;
  21739. }
  21740. while (this._rigCameras.length > 0) {
  21741. var camera = this._rigCameras.pop();
  21742. if (camera) {
  21743. camera.dispose();
  21744. }
  21745. }
  21746. this.cameraRigMode = mode;
  21747. this._cameraRigParams = {};
  21748. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  21749. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  21750. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  21751. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  21752. // create the rig cameras, unless none
  21753. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  21754. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  21755. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  21756. if (leftCamera && rightCamera) {
  21757. this._rigCameras.push(leftCamera);
  21758. this._rigCameras.push(rightCamera);
  21759. }
  21760. }
  21761. switch (this.cameraRigMode) {
  21762. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  21763. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  21764. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  21765. break;
  21766. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  21767. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  21768. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  21769. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  21770. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  21771. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  21772. break;
  21773. case Camera.RIG_MODE_VR:
  21774. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  21775. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  21776. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  21777. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  21778. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  21779. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  21780. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  21781. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  21782. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  21783. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  21784. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  21785. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  21786. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  21787. if (metrics.compensateDistortion) {
  21788. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  21789. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  21790. }
  21791. break;
  21792. case Camera.RIG_MODE_WEBVR:
  21793. if (rigParams.vrDisplay) {
  21794. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  21795. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  21796. //Left eye
  21797. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  21798. this._rigCameras[0].setCameraRigParameter("left", true);
  21799. //leaving this for future reference
  21800. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  21801. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  21802. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  21803. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  21804. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  21805. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  21806. this._rigCameras[0].parent = this;
  21807. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  21808. //Right eye
  21809. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  21810. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  21811. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  21812. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  21813. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  21814. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  21815. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  21816. this._rigCameras[1].parent = this;
  21817. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  21818. if (Camera.UseAlternateWebVRRendering) {
  21819. this._rigCameras[1]._skipRendering = true;
  21820. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  21821. }
  21822. }
  21823. break;
  21824. }
  21825. this._cascadePostProcessesToRigCams();
  21826. this.update();
  21827. };
  21828. Camera.prototype._getVRProjectionMatrix = function () {
  21829. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  21830. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  21831. return this._projectionMatrix;
  21832. };
  21833. Camera.prototype._updateCameraRotationMatrix = function () {
  21834. //Here for WebVR
  21835. };
  21836. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  21837. //Here for WebVR
  21838. };
  21839. /**
  21840. * This function MUST be overwritten by the different WebVR cameras available.
  21841. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  21842. */
  21843. Camera.prototype._getWebVRProjectionMatrix = function () {
  21844. return BABYLON.Matrix.Identity();
  21845. };
  21846. /**
  21847. * This function MUST be overwritten by the different WebVR cameras available.
  21848. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  21849. */
  21850. Camera.prototype._getWebVRViewMatrix = function () {
  21851. return BABYLON.Matrix.Identity();
  21852. };
  21853. Camera.prototype.setCameraRigParameter = function (name, value) {
  21854. if (!this._cameraRigParams) {
  21855. this._cameraRigParams = {};
  21856. }
  21857. this._cameraRigParams[name] = value;
  21858. //provisionnally:
  21859. if (name === "interaxialDistance") {
  21860. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  21861. }
  21862. };
  21863. /**
  21864. * needs to be overridden by children so sub has required properties to be copied
  21865. */
  21866. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  21867. return null;
  21868. };
  21869. /**
  21870. * May need to be overridden by children
  21871. */
  21872. Camera.prototype._updateRigCameras = function () {
  21873. for (var i = 0; i < this._rigCameras.length; i++) {
  21874. this._rigCameras[i].minZ = this.minZ;
  21875. this._rigCameras[i].maxZ = this.maxZ;
  21876. this._rigCameras[i].fov = this.fov;
  21877. }
  21878. // only update viewport when ANAGLYPH
  21879. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  21880. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  21881. }
  21882. };
  21883. Camera.prototype._setupInputs = function () {
  21884. };
  21885. Camera.prototype.serialize = function () {
  21886. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21887. // Type
  21888. serializationObject.type = this.getClassName();
  21889. // Parent
  21890. if (this.parent) {
  21891. serializationObject.parentId = this.parent.id;
  21892. }
  21893. if (this.inputs) {
  21894. this.inputs.serialize(serializationObject);
  21895. }
  21896. // Animations
  21897. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21898. serializationObject.ranges = this.serializeAnimationRanges();
  21899. return serializationObject;
  21900. };
  21901. Camera.prototype.clone = function (name) {
  21902. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  21903. };
  21904. Camera.prototype.getDirection = function (localAxis) {
  21905. var result = BABYLON.Vector3.Zero();
  21906. this.getDirectionToRef(localAxis, result);
  21907. return result;
  21908. };
  21909. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  21910. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  21911. };
  21912. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  21913. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  21914. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  21915. switch (type) {
  21916. case "ArcRotateCamera":
  21917. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  21918. case "DeviceOrientationCamera":
  21919. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  21920. case "FollowCamera":
  21921. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  21922. case "ArcFollowCamera":
  21923. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  21924. case "GamepadCamera":
  21925. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  21926. case "TouchCamera":
  21927. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  21928. case "VirtualJoysticksCamera":
  21929. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  21930. case "WebVRFreeCamera":
  21931. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  21932. case "WebVRGamepadCamera":
  21933. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  21934. case "VRDeviceOrientationFreeCamera":
  21935. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  21936. case "VRDeviceOrientationGamepadCamera":
  21937. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  21938. case "AnaglyphArcRotateCamera":
  21939. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  21940. case "AnaglyphFreeCamera":
  21941. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  21942. case "AnaglyphGamepadCamera":
  21943. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  21944. case "AnaglyphUniversalCamera":
  21945. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  21946. case "StereoscopicArcRotateCamera":
  21947. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  21948. case "StereoscopicFreeCamera":
  21949. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  21950. case "StereoscopicGamepadCamera":
  21951. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  21952. case "StereoscopicUniversalCamera":
  21953. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  21954. case "FreeCamera":// Forcing Universal here
  21955. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  21956. default:// Universal Camera is the default value
  21957. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  21958. }
  21959. };
  21960. Camera.prototype.computeWorldMatrix = function () {
  21961. return this.getWorldMatrix();
  21962. };
  21963. Camera.Parse = function (parsedCamera, scene) {
  21964. var type = parsedCamera.type;
  21965. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  21966. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  21967. // Parent
  21968. if (parsedCamera.parentId) {
  21969. camera._waitingParentId = parsedCamera.parentId;
  21970. }
  21971. //If camera has an input manager, let it parse inputs settings
  21972. if (camera.inputs) {
  21973. camera.inputs.parse(parsedCamera);
  21974. camera._setupInputs();
  21975. }
  21976. if (camera.setPosition) {
  21977. camera.position.copyFromFloats(0, 0, 0);
  21978. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  21979. }
  21980. // Target
  21981. if (parsedCamera.target) {
  21982. if (camera.setTarget) {
  21983. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  21984. }
  21985. }
  21986. // Apply 3d rig, when found
  21987. if (parsedCamera.cameraRigMode) {
  21988. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  21989. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  21990. }
  21991. // Animations
  21992. if (parsedCamera.animations) {
  21993. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  21994. var parsedAnimation = parsedCamera.animations[animationIndex];
  21995. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21996. }
  21997. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  21998. }
  21999. if (parsedCamera.autoAnimate) {
  22000. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22001. }
  22002. return camera;
  22003. };
  22004. // Statics
  22005. Camera._PERSPECTIVE_CAMERA = 0;
  22006. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22007. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22008. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22009. Camera._RIG_MODE_NONE = 0;
  22010. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22011. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22012. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22013. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22014. Camera._RIG_MODE_VR = 20;
  22015. Camera._RIG_MODE_WEBVR = 21;
  22016. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22017. Camera.UseAlternateWebVRRendering = false;
  22018. __decorate([
  22019. BABYLON.serializeAsVector3()
  22020. ], Camera.prototype, "position", void 0);
  22021. __decorate([
  22022. BABYLON.serializeAsVector3()
  22023. ], Camera.prototype, "upVector", void 0);
  22024. __decorate([
  22025. BABYLON.serialize()
  22026. ], Camera.prototype, "orthoLeft", void 0);
  22027. __decorate([
  22028. BABYLON.serialize()
  22029. ], Camera.prototype, "orthoRight", void 0);
  22030. __decorate([
  22031. BABYLON.serialize()
  22032. ], Camera.prototype, "orthoBottom", void 0);
  22033. __decorate([
  22034. BABYLON.serialize()
  22035. ], Camera.prototype, "orthoTop", void 0);
  22036. __decorate([
  22037. BABYLON.serialize()
  22038. ], Camera.prototype, "fov", void 0);
  22039. __decorate([
  22040. BABYLON.serialize()
  22041. ], Camera.prototype, "minZ", void 0);
  22042. __decorate([
  22043. BABYLON.serialize()
  22044. ], Camera.prototype, "maxZ", void 0);
  22045. __decorate([
  22046. BABYLON.serialize()
  22047. ], Camera.prototype, "inertia", void 0);
  22048. __decorate([
  22049. BABYLON.serialize()
  22050. ], Camera.prototype, "mode", void 0);
  22051. __decorate([
  22052. BABYLON.serialize()
  22053. ], Camera.prototype, "layerMask", void 0);
  22054. __decorate([
  22055. BABYLON.serialize()
  22056. ], Camera.prototype, "fovMode", void 0);
  22057. __decorate([
  22058. BABYLON.serialize()
  22059. ], Camera.prototype, "cameraRigMode", void 0);
  22060. __decorate([
  22061. BABYLON.serialize()
  22062. ], Camera.prototype, "interaxialDistance", void 0);
  22063. __decorate([
  22064. BABYLON.serialize()
  22065. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  22066. return Camera;
  22067. }(BABYLON.Node));
  22068. BABYLON.Camera = Camera;
  22069. })(BABYLON || (BABYLON = {}));
  22070. //# sourceMappingURL=babylon.camera.js.map
  22071. "use strict";
  22072. var BABYLON;
  22073. (function (BABYLON) {
  22074. var RenderingManager = /** @class */ (function () {
  22075. function RenderingManager(scene) {
  22076. this._renderingGroups = new Array();
  22077. this._autoClearDepthStencil = {};
  22078. this._customOpaqueSortCompareFn = {};
  22079. this._customAlphaTestSortCompareFn = {};
  22080. this._customTransparentSortCompareFn = {};
  22081. this._renderinGroupInfo = null;
  22082. this._scene = scene;
  22083. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  22084. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  22085. }
  22086. }
  22087. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  22088. if (depth === void 0) { depth = true; }
  22089. if (stencil === void 0) { stencil = true; }
  22090. if (this._depthStencilBufferAlreadyCleaned) {
  22091. return;
  22092. }
  22093. this._scene.getEngine().clear(null, false, depth, stencil);
  22094. this._depthStencilBufferAlreadyCleaned = true;
  22095. };
  22096. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  22097. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  22098. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  22099. var info = null;
  22100. if (observable) {
  22101. if (!this._renderinGroupInfo) {
  22102. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  22103. }
  22104. info = this._renderinGroupInfo;
  22105. info.scene = this._scene;
  22106. info.camera = this._scene.activeCamera;
  22107. }
  22108. // Dispatch sprites
  22109. if (renderSprites) {
  22110. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  22111. var manager = this._scene.spriteManagers[index];
  22112. this.dispatchSprites(manager);
  22113. }
  22114. }
  22115. // Render
  22116. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22117. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  22118. var renderingGroup = this._renderingGroups[index];
  22119. if (!renderingGroup && !observable)
  22120. continue;
  22121. var renderingGroupMask = 0;
  22122. // Fire PRECLEAR stage
  22123. if (observable && info) {
  22124. renderingGroupMask = Math.pow(2, index);
  22125. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  22126. info.renderingGroupId = index;
  22127. observable.notifyObservers(info, renderingGroupMask);
  22128. }
  22129. // Clear depth/stencil if needed
  22130. if (RenderingManager.AUTOCLEAR) {
  22131. var autoClear = this._autoClearDepthStencil[index];
  22132. if (autoClear && autoClear.autoClear) {
  22133. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  22134. }
  22135. }
  22136. if (observable && info) {
  22137. // Fire PREOPAQUE stage
  22138. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  22139. observable.notifyObservers(info, renderingGroupMask);
  22140. // Fire PRETRANSPARENT stage
  22141. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  22142. observable.notifyObservers(info, renderingGroupMask);
  22143. }
  22144. if (renderingGroup)
  22145. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  22146. // Fire POSTTRANSPARENT stage
  22147. if (observable && info) {
  22148. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  22149. observable.notifyObservers(info, renderingGroupMask);
  22150. }
  22151. }
  22152. };
  22153. RenderingManager.prototype.reset = function () {
  22154. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22155. var renderingGroup = this._renderingGroups[index];
  22156. if (renderingGroup) {
  22157. renderingGroup.prepare();
  22158. }
  22159. }
  22160. };
  22161. RenderingManager.prototype.dispose = function () {
  22162. this.freeRenderingGroups();
  22163. this._renderingGroups.length = 0;
  22164. };
  22165. /**
  22166. * Clear the info related to rendering groups preventing retention points during dispose.
  22167. */
  22168. RenderingManager.prototype.freeRenderingGroups = function () {
  22169. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22170. var renderingGroup = this._renderingGroups[index];
  22171. if (renderingGroup) {
  22172. renderingGroup.dispose();
  22173. }
  22174. }
  22175. };
  22176. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  22177. if (this._renderingGroups[renderingGroupId] === undefined) {
  22178. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  22179. }
  22180. };
  22181. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  22182. var renderingGroupId = spriteManager.renderingGroupId || 0;
  22183. this._prepareRenderingGroup(renderingGroupId);
  22184. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  22185. };
  22186. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  22187. var renderingGroupId = particleSystem.renderingGroupId || 0;
  22188. this._prepareRenderingGroup(renderingGroupId);
  22189. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  22190. };
  22191. /**
  22192. * @param subMesh The submesh to dispatch
  22193. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  22194. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  22195. */
  22196. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  22197. if (mesh === undefined) {
  22198. mesh = subMesh.getMesh();
  22199. }
  22200. var renderingGroupId = mesh.renderingGroupId || 0;
  22201. this._prepareRenderingGroup(renderingGroupId);
  22202. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  22203. };
  22204. /**
  22205. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  22206. * This allowed control for front to back rendering or reversly depending of the special needs.
  22207. *
  22208. * @param renderingGroupId The rendering group id corresponding to its index
  22209. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  22210. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  22211. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  22212. */
  22213. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22214. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22215. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22216. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22217. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  22218. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  22219. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  22220. if (this._renderingGroups[renderingGroupId]) {
  22221. var group = this._renderingGroups[renderingGroupId];
  22222. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  22223. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  22224. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  22225. }
  22226. };
  22227. /**
  22228. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  22229. *
  22230. * @param renderingGroupId The rendering group id corresponding to its index
  22231. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  22232. * @param depth Automatically clears depth between groups if true and autoClear is true.
  22233. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  22234. */
  22235. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  22236. if (depth === void 0) { depth = true; }
  22237. if (stencil === void 0) { stencil = true; }
  22238. this._autoClearDepthStencil[renderingGroupId] = {
  22239. autoClear: autoClearDepthStencil,
  22240. depth: depth,
  22241. stencil: stencil
  22242. };
  22243. };
  22244. /**
  22245. * The max id used for rendering groups (not included)
  22246. */
  22247. RenderingManager.MAX_RENDERINGGROUPS = 4;
  22248. /**
  22249. * The min id used for rendering groups (included)
  22250. */
  22251. RenderingManager.MIN_RENDERINGGROUPS = 0;
  22252. /**
  22253. * Used to globally prevent autoclearing scenes.
  22254. */
  22255. RenderingManager.AUTOCLEAR = true;
  22256. return RenderingManager;
  22257. }());
  22258. BABYLON.RenderingManager = RenderingManager;
  22259. })(BABYLON || (BABYLON = {}));
  22260. //# sourceMappingURL=babylon.renderingManager.js.map
  22261. "use strict";
  22262. var BABYLON;
  22263. (function (BABYLON) {
  22264. var RenderingGroup = /** @class */ (function () {
  22265. /**
  22266. * Creates a new rendering group.
  22267. * @param index The rendering group index
  22268. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  22269. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  22270. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  22271. */
  22272. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22273. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22274. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22275. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22276. this.index = index;
  22277. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  22278. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  22279. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  22280. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  22281. this._particleSystems = new BABYLON.SmartArray(256);
  22282. this._spriteManagers = new BABYLON.SmartArray(256);
  22283. this._edgesRenderers = new BABYLON.SmartArray(16);
  22284. this._scene = scene;
  22285. this.opaqueSortCompareFn = opaqueSortCompareFn;
  22286. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  22287. this.transparentSortCompareFn = transparentSortCompareFn;
  22288. }
  22289. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  22290. /**
  22291. * Set the opaque sort comparison function.
  22292. * If null the sub meshes will be render in the order they were created
  22293. */
  22294. set: function (value) {
  22295. this._opaqueSortCompareFn = value;
  22296. if (value) {
  22297. this._renderOpaque = this.renderOpaqueSorted;
  22298. }
  22299. else {
  22300. this._renderOpaque = RenderingGroup.renderUnsorted;
  22301. }
  22302. },
  22303. enumerable: true,
  22304. configurable: true
  22305. });
  22306. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  22307. /**
  22308. * Set the alpha test sort comparison function.
  22309. * If null the sub meshes will be render in the order they were created
  22310. */
  22311. set: function (value) {
  22312. this._alphaTestSortCompareFn = value;
  22313. if (value) {
  22314. this._renderAlphaTest = this.renderAlphaTestSorted;
  22315. }
  22316. else {
  22317. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  22318. }
  22319. },
  22320. enumerable: true,
  22321. configurable: true
  22322. });
  22323. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  22324. /**
  22325. * Set the transparent sort comparison function.
  22326. * If null the sub meshes will be render in the order they were created
  22327. */
  22328. set: function (value) {
  22329. if (value) {
  22330. this._transparentSortCompareFn = value;
  22331. }
  22332. else {
  22333. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  22334. }
  22335. this._renderTransparent = this.renderTransparentSorted;
  22336. },
  22337. enumerable: true,
  22338. configurable: true
  22339. });
  22340. /**
  22341. * Render all the sub meshes contained in the group.
  22342. * @param customRenderFunction Used to override the default render behaviour of the group.
  22343. * @returns true if rendered some submeshes.
  22344. */
  22345. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  22346. if (customRenderFunction) {
  22347. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  22348. return;
  22349. }
  22350. var engine = this._scene.getEngine();
  22351. // Depth only
  22352. if (this._depthOnlySubMeshes.length !== 0) {
  22353. engine.setColorWrite(false);
  22354. this._renderAlphaTest(this._depthOnlySubMeshes);
  22355. engine.setColorWrite(true);
  22356. }
  22357. // Opaque
  22358. if (this._opaqueSubMeshes.length !== 0) {
  22359. this._renderOpaque(this._opaqueSubMeshes);
  22360. }
  22361. // Alpha test
  22362. if (this._alphaTestSubMeshes.length !== 0) {
  22363. this._renderAlphaTest(this._alphaTestSubMeshes);
  22364. }
  22365. var stencilState = engine.getStencilBuffer();
  22366. engine.setStencilBuffer(false);
  22367. // Sprites
  22368. if (renderSprites) {
  22369. this._renderSprites();
  22370. }
  22371. // Particles
  22372. if (renderParticles) {
  22373. this._renderParticles(activeMeshes);
  22374. }
  22375. if (this.onBeforeTransparentRendering) {
  22376. this.onBeforeTransparentRendering();
  22377. }
  22378. // Transparent
  22379. if (this._transparentSubMeshes.length !== 0) {
  22380. this._renderTransparent(this._transparentSubMeshes);
  22381. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22382. }
  22383. // Set back stencil to false in case it changes before the edge renderer.
  22384. engine.setStencilBuffer(false);
  22385. // Edges
  22386. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  22387. this._edgesRenderers.data[edgesRendererIndex].render();
  22388. }
  22389. // Restore Stencil state.
  22390. engine.setStencilBuffer(stencilState);
  22391. };
  22392. /**
  22393. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  22394. * @param subMeshes The submeshes to render
  22395. */
  22396. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  22397. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  22398. };
  22399. /**
  22400. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  22401. * @param subMeshes The submeshes to render
  22402. */
  22403. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  22404. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  22405. };
  22406. /**
  22407. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  22408. * @param subMeshes The submeshes to render
  22409. */
  22410. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  22411. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  22412. };
  22413. /**
  22414. * Renders the submeshes in a specified order.
  22415. * @param subMeshes The submeshes to sort before render
  22416. * @param sortCompareFn The comparison function use to sort
  22417. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  22418. * @param transparent Specifies to activate blending if true
  22419. */
  22420. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  22421. var subIndex = 0;
  22422. var subMesh;
  22423. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  22424. for (; subIndex < subMeshes.length; subIndex++) {
  22425. subMesh = subMeshes.data[subIndex];
  22426. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  22427. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  22428. }
  22429. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  22430. if (sortCompareFn) {
  22431. sortedArray.sort(sortCompareFn);
  22432. }
  22433. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  22434. subMesh = sortedArray[subIndex];
  22435. if (transparent) {
  22436. var material = subMesh.getMaterial();
  22437. if (material && material.needDepthPrePass) {
  22438. var engine = material.getScene().getEngine();
  22439. engine.setColorWrite(false);
  22440. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22441. subMesh.render(false);
  22442. engine.setColorWrite(true);
  22443. }
  22444. }
  22445. subMesh.render(transparent);
  22446. }
  22447. };
  22448. /**
  22449. * Renders the submeshes in the order they were dispatched (no sort applied).
  22450. * @param subMeshes The submeshes to render
  22451. */
  22452. RenderingGroup.renderUnsorted = function (subMeshes) {
  22453. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  22454. var submesh = subMeshes.data[subIndex];
  22455. submesh.render(false);
  22456. }
  22457. };
  22458. /**
  22459. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  22460. * are rendered back to front if in the same alpha index.
  22461. *
  22462. * @param a The first submesh
  22463. * @param b The second submesh
  22464. * @returns The result of the comparison
  22465. */
  22466. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  22467. // Alpha index first
  22468. if (a._alphaIndex > b._alphaIndex) {
  22469. return 1;
  22470. }
  22471. if (a._alphaIndex < b._alphaIndex) {
  22472. return -1;
  22473. }
  22474. // Then distance to camera
  22475. return RenderingGroup.backToFrontSortCompare(a, b);
  22476. };
  22477. /**
  22478. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  22479. * are rendered back to front.
  22480. *
  22481. * @param a The first submesh
  22482. * @param b The second submesh
  22483. * @returns The result of the comparison
  22484. */
  22485. RenderingGroup.backToFrontSortCompare = function (a, b) {
  22486. // Then distance to camera
  22487. if (a._distanceToCamera < b._distanceToCamera) {
  22488. return 1;
  22489. }
  22490. if (a._distanceToCamera > b._distanceToCamera) {
  22491. return -1;
  22492. }
  22493. return 0;
  22494. };
  22495. /**
  22496. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  22497. * are rendered front to back (prevent overdraw).
  22498. *
  22499. * @param a The first submesh
  22500. * @param b The second submesh
  22501. * @returns The result of the comparison
  22502. */
  22503. RenderingGroup.frontToBackSortCompare = function (a, b) {
  22504. // Then distance to camera
  22505. if (a._distanceToCamera < b._distanceToCamera) {
  22506. return -1;
  22507. }
  22508. if (a._distanceToCamera > b._distanceToCamera) {
  22509. return 1;
  22510. }
  22511. return 0;
  22512. };
  22513. /**
  22514. * Resets the different lists of submeshes to prepare a new frame.
  22515. */
  22516. RenderingGroup.prototype.prepare = function () {
  22517. this._opaqueSubMeshes.reset();
  22518. this._transparentSubMeshes.reset();
  22519. this._alphaTestSubMeshes.reset();
  22520. this._depthOnlySubMeshes.reset();
  22521. this._particleSystems.reset();
  22522. this._spriteManagers.reset();
  22523. this._edgesRenderers.reset();
  22524. };
  22525. RenderingGroup.prototype.dispose = function () {
  22526. this._opaqueSubMeshes.dispose();
  22527. this._transparentSubMeshes.dispose();
  22528. this._alphaTestSubMeshes.dispose();
  22529. this._depthOnlySubMeshes.dispose();
  22530. this._particleSystems.dispose();
  22531. this._spriteManagers.dispose();
  22532. this._edgesRenderers.dispose();
  22533. };
  22534. /**
  22535. * Inserts the submesh in its correct queue depending on its material.
  22536. * @param subMesh The submesh to dispatch
  22537. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  22538. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  22539. */
  22540. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  22541. // Get mesh and materials if not provided
  22542. if (mesh === undefined) {
  22543. mesh = subMesh.getMesh();
  22544. }
  22545. if (material === undefined) {
  22546. material = subMesh.getMaterial();
  22547. }
  22548. if (material === null || material === undefined) {
  22549. return;
  22550. }
  22551. if (material.needAlphaBlendingForMesh(mesh)) {
  22552. this._transparentSubMeshes.push(subMesh);
  22553. }
  22554. else if (material.needAlphaTesting()) {
  22555. if (material.needDepthPrePass) {
  22556. this._depthOnlySubMeshes.push(subMesh);
  22557. }
  22558. this._alphaTestSubMeshes.push(subMesh);
  22559. }
  22560. else {
  22561. if (material.needDepthPrePass) {
  22562. this._depthOnlySubMeshes.push(subMesh);
  22563. }
  22564. this._opaqueSubMeshes.push(subMesh); // Opaque
  22565. }
  22566. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  22567. this._edgesRenderers.push(mesh._edgesRenderer);
  22568. }
  22569. };
  22570. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  22571. this._spriteManagers.push(spriteManager);
  22572. };
  22573. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  22574. this._particleSystems.push(particleSystem);
  22575. };
  22576. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  22577. if (this._particleSystems.length === 0) {
  22578. return;
  22579. }
  22580. // Particles
  22581. var activeCamera = this._scene.activeCamera;
  22582. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  22583. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  22584. var particleSystem = this._particleSystems.data[particleIndex];
  22585. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  22586. continue;
  22587. }
  22588. var emitter = particleSystem.emitter;
  22589. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  22590. this._scene._activeParticles.addCount(particleSystem.render(), false);
  22591. }
  22592. }
  22593. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  22594. };
  22595. RenderingGroup.prototype._renderSprites = function () {
  22596. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  22597. return;
  22598. }
  22599. // Sprites
  22600. var activeCamera = this._scene.activeCamera;
  22601. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  22602. for (var id = 0; id < this._spriteManagers.length; id++) {
  22603. var spriteManager = this._spriteManagers.data[id];
  22604. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  22605. spriteManager.render();
  22606. }
  22607. }
  22608. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  22609. };
  22610. return RenderingGroup;
  22611. }());
  22612. BABYLON.RenderingGroup = RenderingGroup;
  22613. })(BABYLON || (BABYLON = {}));
  22614. //# sourceMappingURL=babylon.renderingGroup.js.map
  22615. "use strict";
  22616. var BABYLON;
  22617. (function (BABYLON) {
  22618. /** @ignore */
  22619. var ClickInfo = /** @class */ (function () {
  22620. function ClickInfo() {
  22621. this._singleClick = false;
  22622. this._doubleClick = false;
  22623. this._hasSwiped = false;
  22624. this._ignore = false;
  22625. }
  22626. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  22627. get: function () {
  22628. return this._singleClick;
  22629. },
  22630. set: function (b) {
  22631. this._singleClick = b;
  22632. },
  22633. enumerable: true,
  22634. configurable: true
  22635. });
  22636. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  22637. get: function () {
  22638. return this._doubleClick;
  22639. },
  22640. set: function (b) {
  22641. this._doubleClick = b;
  22642. },
  22643. enumerable: true,
  22644. configurable: true
  22645. });
  22646. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  22647. get: function () {
  22648. return this._hasSwiped;
  22649. },
  22650. set: function (b) {
  22651. this._hasSwiped = b;
  22652. },
  22653. enumerable: true,
  22654. configurable: true
  22655. });
  22656. Object.defineProperty(ClickInfo.prototype, "ignore", {
  22657. get: function () {
  22658. return this._ignore;
  22659. },
  22660. set: function (b) {
  22661. this._ignore = b;
  22662. },
  22663. enumerable: true,
  22664. configurable: true
  22665. });
  22666. return ClickInfo;
  22667. }());
  22668. /**
  22669. * This class is used by the onRenderingGroupObservable
  22670. */
  22671. var RenderingGroupInfo = /** @class */ (function () {
  22672. function RenderingGroupInfo() {
  22673. }
  22674. /**
  22675. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  22676. * This stage will be fired no matter what
  22677. */
  22678. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  22679. /**
  22680. * Called before opaque object are rendered.
  22681. * This stage will be fired only if there's 3D Opaque content to render
  22682. */
  22683. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  22684. /**
  22685. * Called after the opaque objects are rendered and before the transparent ones
  22686. * This stage will be fired only if there's 3D transparent content to render
  22687. */
  22688. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  22689. /**
  22690. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  22691. * This stage will be fired no matter what
  22692. */
  22693. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  22694. return RenderingGroupInfo;
  22695. }());
  22696. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  22697. /**
  22698. * Represents a scene to be rendered by the engine.
  22699. * @see http://doc.babylonjs.com/features/scene
  22700. */
  22701. var Scene = /** @class */ (function () {
  22702. /**
  22703. * Creates a new Scene
  22704. * @param engine defines the engine to use to render this scene
  22705. */
  22706. function Scene(engine) {
  22707. // Members
  22708. /**
  22709. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  22710. */
  22711. this.autoClear = true;
  22712. /**
  22713. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  22714. */
  22715. this.autoClearDepthAndStencil = true;
  22716. /**
  22717. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  22718. */
  22719. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  22720. /**
  22721. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  22722. */
  22723. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  22724. this._forceWireframe = false;
  22725. this._forcePointsCloud = false;
  22726. /**
  22727. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  22728. */
  22729. this.forceShowBoundingBoxes = false;
  22730. /**
  22731. * Gets or sets a boolean indicating if animations are enabled
  22732. */
  22733. this.animationsEnabled = true;
  22734. /**
  22735. * Gets or sets a boolean indicating if a constant deltatime has to be used
  22736. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  22737. */
  22738. this.useConstantAnimationDeltaTime = false;
  22739. /**
  22740. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  22741. * Please note that it requires to run a ray cast through the scene on every frame
  22742. */
  22743. this.constantlyUpdateMeshUnderPointer = false;
  22744. /**
  22745. * Defines the HTML cursor to use when hovering over interactive elements
  22746. */
  22747. this.hoverCursor = "pointer";
  22748. /**
  22749. * Defines the HTML default cursor to use (empty by default)
  22750. */
  22751. this.defaultCursor = "";
  22752. /**
  22753. * This is used to call preventDefault() on pointer down
  22754. * in order to block unwanted artifacts like system double clicks
  22755. */
  22756. this.preventDefaultOnPointerDown = true;
  22757. // Metadata
  22758. /**
  22759. * Gets or sets user defined metadata
  22760. */
  22761. this.metadata = null;
  22762. /**
  22763. * Use this array to add regular expressions used to disable offline support for specific urls
  22764. */
  22765. this.disableOfflineSupportExceptionRules = new Array();
  22766. /**
  22767. * An event triggered when the scene is disposed.
  22768. */
  22769. this.onDisposeObservable = new BABYLON.Observable();
  22770. this._onDisposeObserver = null;
  22771. /**
  22772. * An event triggered before rendering the scene (right after animations and physics)
  22773. */
  22774. this.onBeforeRenderObservable = new BABYLON.Observable();
  22775. this._onBeforeRenderObserver = null;
  22776. /**
  22777. * An event triggered after rendering the scene
  22778. */
  22779. this.onAfterRenderObservable = new BABYLON.Observable();
  22780. this._onAfterRenderObserver = null;
  22781. /**
  22782. * An event triggered before animating the scene
  22783. */
  22784. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  22785. /**
  22786. * An event triggered after animations processing
  22787. */
  22788. this.onAfterAnimationsObservable = new BABYLON.Observable();
  22789. /**
  22790. * An event triggered before draw calls are ready to be sent
  22791. */
  22792. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  22793. /**
  22794. * An event triggered after draw calls have been sent
  22795. */
  22796. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  22797. /**
  22798. * An event triggered when physic simulation is about to be run
  22799. */
  22800. this.onBeforePhysicsObservable = new BABYLON.Observable();
  22801. /**
  22802. * An event triggered when physic simulation has been done
  22803. */
  22804. this.onAfterPhysicsObservable = new BABYLON.Observable();
  22805. /**
  22806. * An event triggered when the scene is ready
  22807. */
  22808. this.onReadyObservable = new BABYLON.Observable();
  22809. /**
  22810. * An event triggered before rendering a camera
  22811. */
  22812. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  22813. this._onBeforeCameraRenderObserver = null;
  22814. /**
  22815. * An event triggered after rendering a camera
  22816. */
  22817. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  22818. this._onAfterCameraRenderObserver = null;
  22819. /**
  22820. * An event triggered when active meshes evaluation is about to start
  22821. */
  22822. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  22823. /**
  22824. * An event triggered when active meshes evaluation is done
  22825. */
  22826. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  22827. /**
  22828. * An event triggered when particles rendering is about to start
  22829. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  22830. */
  22831. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  22832. /**
  22833. * An event triggered when particles rendering is done
  22834. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  22835. */
  22836. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  22837. /**
  22838. * An event triggered when sprites rendering is about to start
  22839. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  22840. */
  22841. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  22842. /**
  22843. * An event triggered when sprites rendering is done
  22844. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  22845. */
  22846. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  22847. /**
  22848. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  22849. */
  22850. this.onDataLoadedObservable = new BABYLON.Observable();
  22851. /**
  22852. * An event triggered when a camera is created
  22853. */
  22854. this.onNewCameraAddedObservable = new BABYLON.Observable();
  22855. /**
  22856. * An event triggered when a camera is removed
  22857. */
  22858. this.onCameraRemovedObservable = new BABYLON.Observable();
  22859. /**
  22860. * An event triggered when a light is created
  22861. */
  22862. this.onNewLightAddedObservable = new BABYLON.Observable();
  22863. /**
  22864. * An event triggered when a light is removed
  22865. */
  22866. this.onLightRemovedObservable = new BABYLON.Observable();
  22867. /**
  22868. * An event triggered when a geometry is created
  22869. */
  22870. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  22871. /**
  22872. * An event triggered when a geometry is removed
  22873. */
  22874. this.onGeometryRemovedObservable = new BABYLON.Observable();
  22875. /**
  22876. * An event triggered when a transform node is created
  22877. */
  22878. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  22879. /**
  22880. * An event triggered when a transform node is removed
  22881. */
  22882. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  22883. /**
  22884. * An event triggered when a mesh is created
  22885. */
  22886. this.onNewMeshAddedObservable = new BABYLON.Observable();
  22887. /**
  22888. * An event triggered when a mesh is removed
  22889. */
  22890. this.onMeshRemovedObservable = new BABYLON.Observable();
  22891. /**
  22892. * An event triggered when render targets are about to be rendered
  22893. * Can happen multiple times per frame.
  22894. */
  22895. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  22896. /**
  22897. * An event triggered when render targets were rendered.
  22898. * Can happen multiple times per frame.
  22899. */
  22900. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  22901. /**
  22902. * An event triggered before calculating deterministic simulation step
  22903. */
  22904. this.onBeforeStepObservable = new BABYLON.Observable();
  22905. /**
  22906. * An event triggered after calculating deterministic simulation step
  22907. */
  22908. this.onAfterStepObservable = new BABYLON.Observable();
  22909. /**
  22910. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  22911. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  22912. * 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)
  22913. */
  22914. this.onRenderingGroupObservable = new BABYLON.Observable();
  22915. // Animations
  22916. /**
  22917. * Gets a list of Animations associated with the scene
  22918. */
  22919. this.animations = [];
  22920. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  22921. /**
  22922. * 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).
  22923. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  22924. */
  22925. this.onPrePointerObservable = new BABYLON.Observable();
  22926. /**
  22927. * Observable event triggered each time an input event is received from the rendering canvas
  22928. */
  22929. this.onPointerObservable = new BABYLON.Observable();
  22930. this._meshPickProceed = false;
  22931. this._currentPickResult = null;
  22932. this._previousPickResult = null;
  22933. this._totalPointersPressed = 0;
  22934. this._doubleClickOccured = false;
  22935. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  22936. this.cameraToUseForPointers = null;
  22937. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  22938. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  22939. this._startingPointerTime = 0;
  22940. this._previousStartingPointerTime = 0;
  22941. // Deterministic lockstep
  22942. this._timeAccumulator = 0;
  22943. this._currentStepId = 0;
  22944. this._currentInternalStep = 0;
  22945. // Keyboard
  22946. /**
  22947. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  22948. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  22949. */
  22950. this.onPreKeyboardObservable = new BABYLON.Observable();
  22951. /**
  22952. * Observable event triggered each time an keyboard event is received from the hosting window
  22953. */
  22954. this.onKeyboardObservable = new BABYLON.Observable();
  22955. // Coordinates system
  22956. this._useRightHandedSystem = false;
  22957. // Fog
  22958. this._fogEnabled = true;
  22959. this._fogMode = Scene.FOGMODE_NONE;
  22960. /**
  22961. * Gets or sets the fog color to use
  22962. * @see http://doc.babylonjs.com/babylon101/environment#fog
  22963. */
  22964. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  22965. /**
  22966. * Gets or sets the fog density to use
  22967. * @see http://doc.babylonjs.com/babylon101/environment#fog
  22968. */
  22969. this.fogDensity = 0.1;
  22970. /**
  22971. * Gets or sets the fog start distance to use
  22972. * @see http://doc.babylonjs.com/babylon101/environment#fog
  22973. */
  22974. this.fogStart = 0;
  22975. /**
  22976. * Gets or sets the fog end distance to use
  22977. * @see http://doc.babylonjs.com/babylon101/environment#fog
  22978. */
  22979. this.fogEnd = 1000.0;
  22980. // Lights
  22981. this._shadowsEnabled = true;
  22982. this._lightsEnabled = true;
  22983. /**
  22984. * All of the lights added to this scene
  22985. * @see http://doc.babylonjs.com/babylon101/lights
  22986. */
  22987. this.lights = new Array();
  22988. // Cameras
  22989. /** All of the cameras added to this scene.
  22990. * @see http://doc.babylonjs.com/babylon101/cameras
  22991. */
  22992. this.cameras = new Array();
  22993. /** All of the active cameras added to this scene. */
  22994. this.activeCameras = new Array();
  22995. // Meshes
  22996. /**
  22997. * All of the tranform nodes added to this scene
  22998. * @see http://doc.babylonjs.com/how_to/transformnode
  22999. */
  23000. this.transformNodes = new Array();
  23001. /**
  23002. * All of the (abstract) meshes added to this scene
  23003. */
  23004. this.meshes = new Array();
  23005. /**
  23006. * All of the animation groups added to this scene
  23007. * @see http://doc.babylonjs.com/how_to/group
  23008. */
  23009. this.animationGroups = new Array();
  23010. // Geometries
  23011. this._geometries = new Array();
  23012. /**
  23013. * All of the materials added to this scene
  23014. * @see http://doc.babylonjs.com/babylon101/materials
  23015. */
  23016. this.materials = new Array();
  23017. /**
  23018. * All of the multi-materials added to this scene
  23019. * @see http://doc.babylonjs.com/how_to/multi_materials
  23020. */
  23021. this.multiMaterials = new Array();
  23022. // Textures
  23023. this._texturesEnabled = true;
  23024. /**
  23025. * All of the textures added to this scene
  23026. */
  23027. this.textures = new Array();
  23028. // Particles
  23029. /**
  23030. * Gets or sets a boolean indicating if particles are enabled on this scene
  23031. */
  23032. this.particlesEnabled = true;
  23033. /**
  23034. * All of the particle systems added to this scene
  23035. * @see http://doc.babylonjs.com/babylon101/particles
  23036. */
  23037. this.particleSystems = new Array();
  23038. // Sprites
  23039. /**
  23040. * Gets or sets a boolean indicating if sprites are enabled on this scene
  23041. */
  23042. this.spritesEnabled = true;
  23043. /**
  23044. * All of the sprite managers added to this scene
  23045. * @see http://doc.babylonjs.com/babylon101/sprites
  23046. */
  23047. this.spriteManagers = new Array();
  23048. /**
  23049. * The list of layers (background and foreground) of the scene
  23050. */
  23051. this.layers = new Array();
  23052. /**
  23053. * The list of effect layers (highlights/glow) added to the scene
  23054. * @see http://doc.babylonjs.com/how_to/highlight_layer
  23055. * @see http://doc.babylonjs.com/how_to/glow_layer
  23056. */
  23057. this.effectLayers = new Array();
  23058. // Skeletons
  23059. this._skeletonsEnabled = true;
  23060. /**
  23061. * The list of skeletons added to the scene
  23062. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23063. */
  23064. this.skeletons = new Array();
  23065. // Morph targets
  23066. /**
  23067. * The list of morph target managers added to the scene
  23068. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23069. */
  23070. this.morphTargetManagers = new Array();
  23071. // Lens flares
  23072. /**
  23073. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  23074. */
  23075. this.lensFlaresEnabled = true;
  23076. /**
  23077. * The list of lens flare system added to the scene
  23078. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  23079. */
  23080. this.lensFlareSystems = new Array();
  23081. // Collisions
  23082. /**
  23083. * Gets or sets a boolean indicating if collisions are enabled on this scene
  23084. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23085. */
  23086. this.collisionsEnabled = true;
  23087. /**
  23088. * Defines the gravity applied to this scene (used only for collisions)
  23089. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23090. */
  23091. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  23092. // Postprocesses
  23093. /**
  23094. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  23095. */
  23096. this.postProcessesEnabled = true;
  23097. /**
  23098. * The list of postprocesses added to the scene
  23099. */
  23100. this.postProcesses = new Array();
  23101. // Customs render targets
  23102. /**
  23103. * Gets or sets a boolean indicating if render targets are enabled on this scene
  23104. */
  23105. this.renderTargetsEnabled = true;
  23106. /**
  23107. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  23108. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  23109. */
  23110. this.dumpNextRenderTargets = false;
  23111. /**
  23112. * The list of user defined render targets added to the scene
  23113. */
  23114. this.customRenderTargets = new Array();
  23115. /**
  23116. * Gets the list of meshes imported to the scene through SceneLoader
  23117. */
  23118. this.importedMeshesFiles = new Array();
  23119. // Probes
  23120. /**
  23121. * Gets or sets a boolean indicating if probes are enabled on this scene
  23122. */
  23123. this.probesEnabled = true;
  23124. /**
  23125. * The list of reflection probes added to the scene
  23126. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  23127. */
  23128. this.reflectionProbes = new Array();
  23129. /** @ignore */
  23130. this._actionManagers = new Array();
  23131. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  23132. // Procedural textures
  23133. /**
  23134. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  23135. */
  23136. this.proceduralTexturesEnabled = true;
  23137. /**
  23138. * The list of procedural textures added to the scene
  23139. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  23140. */
  23141. this.proceduralTextures = new Array();
  23142. /**
  23143. * The list of sound tracks added to the scene
  23144. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  23145. */
  23146. this.soundTracks = new Array();
  23147. this._audioEnabled = true;
  23148. this._headphone = false;
  23149. // Performance counters
  23150. this._totalVertices = new BABYLON.PerfCounter();
  23151. /** @ignore */
  23152. this._activeIndices = new BABYLON.PerfCounter();
  23153. /** @ignore */
  23154. this._activeParticles = new BABYLON.PerfCounter();
  23155. /** @ignore */
  23156. this._activeBones = new BABYLON.PerfCounter();
  23157. this._animationTime = 0;
  23158. /**
  23159. * Gets or sets a general scale for animation speed
  23160. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  23161. */
  23162. this.animationTimeScale = 1;
  23163. this._renderId = 0;
  23164. this._executeWhenReadyTimeoutId = -1;
  23165. this._intermediateRendering = false;
  23166. this._viewUpdateFlag = -1;
  23167. this._projectionUpdateFlag = -1;
  23168. this._alternateViewUpdateFlag = -1;
  23169. this._alternateProjectionUpdateFlag = -1;
  23170. /** @ignore */
  23171. this._toBeDisposed = new BABYLON.SmartArray(256);
  23172. this._activeRequests = new Array();
  23173. this._pendingData = new Array();
  23174. this._isDisposed = false;
  23175. /**
  23176. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  23177. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  23178. */
  23179. this.dispatchAllSubMeshesOfActiveMeshes = false;
  23180. this._activeMeshes = new BABYLON.SmartArray(256);
  23181. this._processedMaterials = new BABYLON.SmartArray(256);
  23182. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  23183. /** @ignore */
  23184. this._activeParticleSystems = new BABYLON.SmartArray(256);
  23185. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  23186. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  23187. /** @ignore */
  23188. this._activeAnimatables = new Array();
  23189. this._transformMatrix = BABYLON.Matrix.Zero();
  23190. this._useAlternateCameraConfiguration = false;
  23191. this._alternateRendering = false;
  23192. /**
  23193. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  23194. * This is useful if there are more lights that the maximum simulteanous authorized
  23195. */
  23196. this.requireLightSorting = false;
  23197. this._depthRenderer = {};
  23198. this._activeMeshesFrozen = false;
  23199. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  23200. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  23201. this._engine.scenes.push(this);
  23202. this._uid = null;
  23203. this._renderingManager = new BABYLON.RenderingManager(this);
  23204. this.postProcessManager = new BABYLON.PostProcessManager(this);
  23205. if (BABYLON.OutlineRenderer) {
  23206. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  23207. }
  23208. if (BABYLON.Tools.IsWindowObjectExist()) {
  23209. this.attachControl();
  23210. }
  23211. //simplification queue
  23212. if (BABYLON.SimplificationQueue) {
  23213. this.simplificationQueue = new BABYLON.SimplificationQueue();
  23214. }
  23215. //collision coordinator initialization. For now legacy per default.
  23216. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  23217. // Uniform Buffer
  23218. this._createUbo();
  23219. // Default Image processing definition.
  23220. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  23221. }
  23222. Object.defineProperty(Scene, "FOGMODE_NONE", {
  23223. /** The fog is deactivated */
  23224. get: function () {
  23225. return Scene._FOGMODE_NONE;
  23226. },
  23227. enumerable: true,
  23228. configurable: true
  23229. });
  23230. Object.defineProperty(Scene, "FOGMODE_EXP", {
  23231. /** The fog density is following an exponential function */
  23232. get: function () {
  23233. return Scene._FOGMODE_EXP;
  23234. },
  23235. enumerable: true,
  23236. configurable: true
  23237. });
  23238. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  23239. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  23240. get: function () {
  23241. return Scene._FOGMODE_EXP2;
  23242. },
  23243. enumerable: true,
  23244. configurable: true
  23245. });
  23246. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  23247. /** The fog density is following a linear function. */
  23248. get: function () {
  23249. return Scene._FOGMODE_LINEAR;
  23250. },
  23251. enumerable: true,
  23252. configurable: true
  23253. });
  23254. Object.defineProperty(Scene.prototype, "environmentTexture", {
  23255. /**
  23256. * Texture used in all pbr material as the reflection texture.
  23257. * As in the majority of the scene they are the same (exception for multi room and so on),
  23258. * this is easier to reference from here than from all the materials.
  23259. */
  23260. get: function () {
  23261. return this._environmentTexture;
  23262. },
  23263. /**
  23264. * Texture used in all pbr material as the reflection texture.
  23265. * As in the majority of the scene they are the same (exception for multi room and so on),
  23266. * this is easier to set here than in all the materials.
  23267. */
  23268. set: function (value) {
  23269. if (this._environmentTexture === value) {
  23270. return;
  23271. }
  23272. this._environmentTexture = value;
  23273. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23274. },
  23275. enumerable: true,
  23276. configurable: true
  23277. });
  23278. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  23279. /**
  23280. * Default image processing configuration used either in the rendering
  23281. * Forward main pass or through the imageProcessingPostProcess if present.
  23282. * As in the majority of the scene they are the same (exception for multi camera),
  23283. * this is easier to reference from here than from all the materials and post process.
  23284. *
  23285. * No setter as we it is a shared configuration, you can set the values instead.
  23286. */
  23287. get: function () {
  23288. return this._imageProcessingConfiguration;
  23289. },
  23290. enumerable: true,
  23291. configurable: true
  23292. });
  23293. Object.defineProperty(Scene.prototype, "forceWireframe", {
  23294. get: function () {
  23295. return this._forceWireframe;
  23296. },
  23297. /**
  23298. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  23299. */
  23300. set: function (value) {
  23301. if (this._forceWireframe === value) {
  23302. return;
  23303. }
  23304. this._forceWireframe = value;
  23305. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23306. },
  23307. enumerable: true,
  23308. configurable: true
  23309. });
  23310. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  23311. get: function () {
  23312. return this._forcePointsCloud;
  23313. },
  23314. /**
  23315. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  23316. */
  23317. set: function (value) {
  23318. if (this._forcePointsCloud === value) {
  23319. return;
  23320. }
  23321. this._forcePointsCloud = value;
  23322. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23323. },
  23324. enumerable: true,
  23325. configurable: true
  23326. });
  23327. Object.defineProperty(Scene.prototype, "onDispose", {
  23328. /** Sets a function to be executed when this scene is disposed. */
  23329. set: function (callback) {
  23330. if (this._onDisposeObserver) {
  23331. this.onDisposeObservable.remove(this._onDisposeObserver);
  23332. }
  23333. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23334. },
  23335. enumerable: true,
  23336. configurable: true
  23337. });
  23338. Object.defineProperty(Scene.prototype, "beforeRender", {
  23339. /** Sets a function to be executed before rendering this scene */
  23340. set: function (callback) {
  23341. if (this._onBeforeRenderObserver) {
  23342. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  23343. }
  23344. if (callback) {
  23345. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  23346. }
  23347. },
  23348. enumerable: true,
  23349. configurable: true
  23350. });
  23351. Object.defineProperty(Scene.prototype, "afterRender", {
  23352. /** Sets a function to be executed after rendering this scene */
  23353. set: function (callback) {
  23354. if (this._onAfterRenderObserver) {
  23355. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  23356. }
  23357. if (callback) {
  23358. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  23359. }
  23360. },
  23361. enumerable: true,
  23362. configurable: true
  23363. });
  23364. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  23365. /** Sets a function to be executed before rendering a camera*/
  23366. set: function (callback) {
  23367. if (this._onBeforeCameraRenderObserver) {
  23368. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  23369. }
  23370. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  23371. },
  23372. enumerable: true,
  23373. configurable: true
  23374. });
  23375. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  23376. /** Sets a function to be executed after rendering a camera*/
  23377. set: function (callback) {
  23378. if (this._onAfterCameraRenderObserver) {
  23379. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  23380. }
  23381. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  23382. },
  23383. enumerable: true,
  23384. configurable: true
  23385. });
  23386. Object.defineProperty(Scene.prototype, "gamepadManager", {
  23387. /**
  23388. * Gets the gamepad manager associated with the scene
  23389. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  23390. */
  23391. get: function () {
  23392. if (!this._gamepadManager) {
  23393. this._gamepadManager = new BABYLON.GamepadManager(this);
  23394. }
  23395. return this._gamepadManager;
  23396. },
  23397. enumerable: true,
  23398. configurable: true
  23399. });
  23400. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  23401. /**
  23402. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  23403. */
  23404. get: function () {
  23405. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  23406. },
  23407. enumerable: true,
  23408. configurable: true
  23409. });
  23410. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  23411. get: function () {
  23412. return this._useRightHandedSystem;
  23413. },
  23414. /**
  23415. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  23416. */
  23417. set: function (value) {
  23418. if (this._useRightHandedSystem === value) {
  23419. return;
  23420. }
  23421. this._useRightHandedSystem = value;
  23422. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23423. },
  23424. enumerable: true,
  23425. configurable: true
  23426. });
  23427. /**
  23428. * Sets the step Id used by deterministic lock step
  23429. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  23430. * @param newStepId defines the step Id
  23431. */
  23432. Scene.prototype.setStepId = function (newStepId) {
  23433. this._currentStepId = newStepId;
  23434. };
  23435. ;
  23436. /**
  23437. * Gets the step Id used by deterministic lock step
  23438. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  23439. * @returns the step Id
  23440. */
  23441. Scene.prototype.getStepId = function () {
  23442. return this._currentStepId;
  23443. };
  23444. ;
  23445. /**
  23446. * Gets the internal step used by deterministic lock step
  23447. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  23448. * @returns the internal step
  23449. */
  23450. Scene.prototype.getInternalStep = function () {
  23451. return this._currentInternalStep;
  23452. };
  23453. ;
  23454. Object.defineProperty(Scene.prototype, "fogEnabled", {
  23455. get: function () {
  23456. return this._fogEnabled;
  23457. },
  23458. /**
  23459. * Gets or sets a boolean indicating if fog is enabled on this scene
  23460. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23461. */
  23462. set: function (value) {
  23463. if (this._fogEnabled === value) {
  23464. return;
  23465. }
  23466. this._fogEnabled = value;
  23467. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23468. },
  23469. enumerable: true,
  23470. configurable: true
  23471. });
  23472. Object.defineProperty(Scene.prototype, "fogMode", {
  23473. get: function () {
  23474. return this._fogMode;
  23475. },
  23476. /**
  23477. * Gets or sets the fog mode to use
  23478. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23479. */
  23480. set: function (value) {
  23481. if (this._fogMode === value) {
  23482. return;
  23483. }
  23484. this._fogMode = value;
  23485. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23486. },
  23487. enumerable: true,
  23488. configurable: true
  23489. });
  23490. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  23491. get: function () {
  23492. return this._shadowsEnabled;
  23493. },
  23494. /**
  23495. * Gets or sets a boolean indicating if shadows are enabled on this scene
  23496. */
  23497. set: function (value) {
  23498. if (this._shadowsEnabled === value) {
  23499. return;
  23500. }
  23501. this._shadowsEnabled = value;
  23502. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  23503. },
  23504. enumerable: true,
  23505. configurable: true
  23506. });
  23507. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  23508. get: function () {
  23509. return this._lightsEnabled;
  23510. },
  23511. /**
  23512. * Gets or sets a boolean indicating if lights are enabled on this scene
  23513. */
  23514. set: function (value) {
  23515. if (this._lightsEnabled === value) {
  23516. return;
  23517. }
  23518. this._lightsEnabled = value;
  23519. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  23520. },
  23521. enumerable: true,
  23522. configurable: true
  23523. });
  23524. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  23525. /** The default material used on meshes when no material is affected */
  23526. get: function () {
  23527. if (!this._defaultMaterial) {
  23528. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  23529. }
  23530. return this._defaultMaterial;
  23531. },
  23532. /** The default material used on meshes when no material is affected */
  23533. set: function (value) {
  23534. this._defaultMaterial = value;
  23535. },
  23536. enumerable: true,
  23537. configurable: true
  23538. });
  23539. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  23540. get: function () {
  23541. return this._texturesEnabled;
  23542. },
  23543. /**
  23544. * Gets or sets a boolean indicating if textures are enabled on this scene
  23545. */
  23546. set: function (value) {
  23547. if (this._texturesEnabled === value) {
  23548. return;
  23549. }
  23550. this._texturesEnabled = value;
  23551. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23552. },
  23553. enumerable: true,
  23554. configurable: true
  23555. });
  23556. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  23557. get: function () {
  23558. return this._skeletonsEnabled;
  23559. },
  23560. /**
  23561. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  23562. */
  23563. set: function (value) {
  23564. if (this._skeletonsEnabled === value) {
  23565. return;
  23566. }
  23567. this._skeletonsEnabled = value;
  23568. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  23569. },
  23570. enumerable: true,
  23571. configurable: true
  23572. });
  23573. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  23574. /**
  23575. * Gets the postprocess render pipeline manager
  23576. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  23577. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  23578. */
  23579. get: function () {
  23580. if (!this._postProcessRenderPipelineManager) {
  23581. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  23582. }
  23583. return this._postProcessRenderPipelineManager;
  23584. },
  23585. enumerable: true,
  23586. configurable: true
  23587. });
  23588. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  23589. /**
  23590. * Gets the main soundtrack associated with the scene
  23591. */
  23592. get: function () {
  23593. if (!this._mainSoundTrack) {
  23594. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  23595. }
  23596. return this._mainSoundTrack;
  23597. },
  23598. enumerable: true,
  23599. configurable: true
  23600. });
  23601. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  23602. /** @ignore */
  23603. get: function () {
  23604. return this._alternateRendering;
  23605. },
  23606. enumerable: true,
  23607. configurable: true
  23608. });
  23609. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  23610. /**
  23611. * Gets the list of frustum planes (built from the active camera)
  23612. */
  23613. get: function () {
  23614. return this._frustumPlanes;
  23615. },
  23616. enumerable: true,
  23617. configurable: true
  23618. });
  23619. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  23620. /**
  23621. * Gets the current geometry buffer associated to the scene.
  23622. */
  23623. get: function () {
  23624. return this._geometryBufferRenderer;
  23625. },
  23626. /**
  23627. * Sets the current geometry buffer for the scene.
  23628. */
  23629. set: function (geometryBufferRenderer) {
  23630. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  23631. this._geometryBufferRenderer = geometryBufferRenderer;
  23632. }
  23633. },
  23634. enumerable: true,
  23635. configurable: true
  23636. });
  23637. Object.defineProperty(Scene.prototype, "debugLayer", {
  23638. /**
  23639. * Gets the debug layer associated with the scene
  23640. * @see http://doc.babylonjs.com/features/playground_debuglayer
  23641. */
  23642. get: function () {
  23643. if (!this._debugLayer) {
  23644. this._debugLayer = new BABYLON.DebugLayer(this);
  23645. }
  23646. return this._debugLayer;
  23647. },
  23648. enumerable: true,
  23649. configurable: true
  23650. });
  23651. Object.defineProperty(Scene.prototype, "workerCollisions", {
  23652. /**
  23653. * Gets a boolean indicating if collisions are processed on a web worker
  23654. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  23655. */
  23656. get: function () {
  23657. return this._workerCollisions;
  23658. },
  23659. set: function (enabled) {
  23660. if (!BABYLON.CollisionCoordinatorLegacy) {
  23661. return;
  23662. }
  23663. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  23664. this._workerCollisions = enabled;
  23665. if (this.collisionCoordinator) {
  23666. this.collisionCoordinator.destroy();
  23667. }
  23668. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  23669. this.collisionCoordinator.init(this);
  23670. },
  23671. enumerable: true,
  23672. configurable: true
  23673. });
  23674. Object.defineProperty(Scene.prototype, "selectionOctree", {
  23675. /**
  23676. * Gets the octree used to boost mesh selection (picking)
  23677. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  23678. */
  23679. get: function () {
  23680. return this._selectionOctree;
  23681. },
  23682. enumerable: true,
  23683. configurable: true
  23684. });
  23685. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  23686. /**
  23687. * Gets the mesh that is currently under the pointer
  23688. */
  23689. get: function () {
  23690. return this._pointerOverMesh;
  23691. },
  23692. enumerable: true,
  23693. configurable: true
  23694. });
  23695. Object.defineProperty(Scene.prototype, "pointerX", {
  23696. /**
  23697. * Gets the current on-screen X position of the pointer
  23698. */
  23699. get: function () {
  23700. return this._pointerX;
  23701. },
  23702. enumerable: true,
  23703. configurable: true
  23704. });
  23705. Object.defineProperty(Scene.prototype, "pointerY", {
  23706. /**
  23707. * Gets the current on-screen Y position of the pointer
  23708. */
  23709. get: function () {
  23710. return this._pointerY;
  23711. },
  23712. enumerable: true,
  23713. configurable: true
  23714. });
  23715. /**
  23716. * Gets the cached material (ie. the latest rendered one)
  23717. * @returns the cached material
  23718. */
  23719. Scene.prototype.getCachedMaterial = function () {
  23720. return this._cachedMaterial;
  23721. };
  23722. /**
  23723. * Gets the cached effect (ie. the latest rendered one)
  23724. * @returns the cached effect
  23725. */
  23726. Scene.prototype.getCachedEffect = function () {
  23727. return this._cachedEffect;
  23728. };
  23729. /**
  23730. * Gets the cached visibility state (ie. the latest rendered one)
  23731. * @returns the cached visibility state
  23732. */
  23733. Scene.prototype.getCachedVisibility = function () {
  23734. return this._cachedVisibility;
  23735. };
  23736. /**
  23737. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  23738. * @param material defines the current material
  23739. * @param effect defines the current effect
  23740. * @param visibility defines the current visibility state
  23741. * @returns true if one parameter is not cached
  23742. */
  23743. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  23744. if (visibility === void 0) { visibility = 1; }
  23745. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  23746. };
  23747. /**
  23748. * Gets the bounding box renderer associated with the scene
  23749. * @returns a BoundingBoxRenderer
  23750. */
  23751. Scene.prototype.getBoundingBoxRenderer = function () {
  23752. if (!this._boundingBoxRenderer) {
  23753. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  23754. }
  23755. return this._boundingBoxRenderer;
  23756. };
  23757. /**
  23758. * Gets the outline renderer associated with the scene
  23759. * @returns a OutlineRenderer
  23760. */
  23761. Scene.prototype.getOutlineRenderer = function () {
  23762. return this._outlineRenderer;
  23763. };
  23764. /**
  23765. * Gets the engine associated with the scene
  23766. * @returns an Engine
  23767. */
  23768. Scene.prototype.getEngine = function () {
  23769. return this._engine;
  23770. };
  23771. /**
  23772. * Gets the total number of vertices rendered per frame
  23773. * @returns the total number of vertices rendered per frame
  23774. */
  23775. Scene.prototype.getTotalVertices = function () {
  23776. return this._totalVertices.current;
  23777. };
  23778. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  23779. /**
  23780. * Gets the performance counter for total vertices
  23781. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  23782. */
  23783. get: function () {
  23784. return this._totalVertices;
  23785. },
  23786. enumerable: true,
  23787. configurable: true
  23788. });
  23789. /**
  23790. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  23791. * @returns the total number of active indices rendered per frame
  23792. */
  23793. Scene.prototype.getActiveIndices = function () {
  23794. return this._activeIndices.current;
  23795. };
  23796. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  23797. /**
  23798. * Gets the performance counter for active indices
  23799. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  23800. */
  23801. get: function () {
  23802. return this._activeIndices;
  23803. },
  23804. enumerable: true,
  23805. configurable: true
  23806. });
  23807. /**
  23808. * Gets the total number of active particles rendered per frame
  23809. * @returns the total number of active particles rendered per frame
  23810. */
  23811. Scene.prototype.getActiveParticles = function () {
  23812. return this._activeParticles.current;
  23813. };
  23814. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  23815. /**
  23816. * Gets the performance counter for active particles
  23817. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  23818. */
  23819. get: function () {
  23820. return this._activeParticles;
  23821. },
  23822. enumerable: true,
  23823. configurable: true
  23824. });
  23825. /**
  23826. * Gets the total number of active bones rendered per frame
  23827. * @returns the total number of active bones rendered per frame
  23828. */
  23829. Scene.prototype.getActiveBones = function () {
  23830. return this._activeBones.current;
  23831. };
  23832. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  23833. /**
  23834. * Gets the performance counter for active bones
  23835. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  23836. */
  23837. get: function () {
  23838. return this._activeBones;
  23839. },
  23840. enumerable: true,
  23841. configurable: true
  23842. });
  23843. /** @ignore */
  23844. Scene.prototype.getInterFramePerfCounter = function () {
  23845. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  23846. return 0;
  23847. };
  23848. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  23849. /** @ignore */
  23850. get: function () {
  23851. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  23852. return null;
  23853. },
  23854. enumerable: true,
  23855. configurable: true
  23856. });
  23857. /** @ignore */
  23858. Scene.prototype.getLastFrameDuration = function () {
  23859. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  23860. return 0;
  23861. };
  23862. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  23863. /** @ignore */
  23864. get: function () {
  23865. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  23866. return null;
  23867. },
  23868. enumerable: true,
  23869. configurable: true
  23870. });
  23871. /** @ignore */
  23872. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  23873. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  23874. return 0;
  23875. };
  23876. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  23877. /** @ignore */
  23878. get: function () {
  23879. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  23880. return null;
  23881. },
  23882. enumerable: true,
  23883. configurable: true
  23884. });
  23885. /**
  23886. * Gets the array of active meshes
  23887. * @returns an array of AbstractMesh
  23888. */
  23889. Scene.prototype.getActiveMeshes = function () {
  23890. return this._activeMeshes;
  23891. };
  23892. /** @ignore */
  23893. Scene.prototype.getRenderTargetsDuration = function () {
  23894. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  23895. return 0;
  23896. };
  23897. /** @ignore */
  23898. Scene.prototype.getRenderDuration = function () {
  23899. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  23900. return 0;
  23901. };
  23902. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  23903. /** @ignore */
  23904. get: function () {
  23905. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  23906. return null;
  23907. },
  23908. enumerable: true,
  23909. configurable: true
  23910. });
  23911. /** @ignore */
  23912. Scene.prototype.getParticlesDuration = function () {
  23913. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  23914. return 0;
  23915. };
  23916. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  23917. /** @ignore */
  23918. get: function () {
  23919. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  23920. return null;
  23921. },
  23922. enumerable: true,
  23923. configurable: true
  23924. });
  23925. /** @ignore */
  23926. Scene.prototype.getSpritesDuration = function () {
  23927. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  23928. return 0;
  23929. };
  23930. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  23931. /** @ignore */
  23932. get: function () {
  23933. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  23934. return null;
  23935. },
  23936. enumerable: true,
  23937. configurable: true
  23938. });
  23939. /**
  23940. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  23941. * @returns a number
  23942. */
  23943. Scene.prototype.getAnimationRatio = function () {
  23944. return this._animationRatio;
  23945. };
  23946. /**
  23947. * Gets an unique Id for the current frame
  23948. * @returns a number
  23949. */
  23950. Scene.prototype.getRenderId = function () {
  23951. return this._renderId;
  23952. };
  23953. /** Call this function if you want to manually increment the render Id*/
  23954. Scene.prototype.incrementRenderId = function () {
  23955. this._renderId++;
  23956. };
  23957. Scene.prototype._updatePointerPosition = function (evt) {
  23958. var canvasRect = this._engine.getRenderingCanvasClientRect();
  23959. if (!canvasRect) {
  23960. return;
  23961. }
  23962. this._pointerX = evt.clientX - canvasRect.left;
  23963. this._pointerY = evt.clientY - canvasRect.top;
  23964. this._unTranslatedPointerX = this._pointerX;
  23965. this._unTranslatedPointerY = this._pointerY;
  23966. };
  23967. Scene.prototype._createUbo = function () {
  23968. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  23969. this._sceneUbo.addUniform("viewProjection", 16);
  23970. this._sceneUbo.addUniform("view", 16);
  23971. };
  23972. Scene.prototype._createAlternateUbo = function () {
  23973. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  23974. this._alternateSceneUbo.addUniform("viewProjection", 16);
  23975. this._alternateSceneUbo.addUniform("view", 16);
  23976. };
  23977. // Pointers handling
  23978. /**
  23979. * Use this method to simulate a pointer move on a mesh
  23980. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  23981. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  23982. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  23983. * @returns the current scene
  23984. */
  23985. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  23986. var evt = new PointerEvent("pointermove", pointerEventInit);
  23987. return this._processPointerMove(pickResult, evt);
  23988. };
  23989. Scene.prototype._processPointerMove = function (pickResult, evt) {
  23990. var canvas = this._engine.getRenderingCanvas();
  23991. if (!canvas) {
  23992. return this;
  23993. }
  23994. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  23995. this.setPointerOverSprite(null);
  23996. this.setPointerOverMesh(pickResult.pickedMesh);
  23997. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  23998. if (this._pointerOverMesh.actionManager.hoverCursor) {
  23999. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  24000. }
  24001. else {
  24002. canvas.style.cursor = this.hoverCursor;
  24003. }
  24004. }
  24005. else {
  24006. canvas.style.cursor = this.defaultCursor;
  24007. }
  24008. }
  24009. else {
  24010. this.setPointerOverMesh(null);
  24011. // Sprites
  24012. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  24013. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24014. this.setPointerOverSprite(pickResult.pickedSprite);
  24015. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  24016. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  24017. }
  24018. else {
  24019. canvas.style.cursor = this.hoverCursor;
  24020. }
  24021. }
  24022. else {
  24023. this.setPointerOverSprite(null);
  24024. // Restore pointer
  24025. canvas.style.cursor = this.defaultCursor;
  24026. }
  24027. }
  24028. if (pickResult) {
  24029. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24030. if (this.onPointerMove) {
  24031. this.onPointerMove(evt, pickResult, type);
  24032. }
  24033. if (this.onPointerObservable.hasObservers()) {
  24034. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24035. this.onPointerObservable.notifyObservers(pi, type);
  24036. }
  24037. }
  24038. return this;
  24039. };
  24040. /**
  24041. * Use this method to simulate a pointer down on a mesh
  24042. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24043. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24044. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24045. * @returns the current scene
  24046. */
  24047. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  24048. var evt = new PointerEvent("pointerdown", pointerEventInit);
  24049. return this._processPointerDown(pickResult, evt);
  24050. };
  24051. Scene.prototype._processPointerDown = function (pickResult, evt) {
  24052. var _this = this;
  24053. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24054. this._pickedDownMesh = pickResult.pickedMesh;
  24055. var actionManager = pickResult.pickedMesh.actionManager;
  24056. if (actionManager) {
  24057. if (actionManager.hasPickTriggers) {
  24058. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24059. switch (evt.button) {
  24060. case 0:
  24061. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24062. break;
  24063. case 1:
  24064. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24065. break;
  24066. case 2:
  24067. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24068. break;
  24069. }
  24070. }
  24071. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  24072. window.setTimeout(function () {
  24073. 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);
  24074. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  24075. if (_this._totalPointersPressed !== 0 &&
  24076. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  24077. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  24078. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  24079. _this._startingPointerTime = 0;
  24080. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24081. }
  24082. }
  24083. }, Scene.LongPressDelay);
  24084. }
  24085. }
  24086. }
  24087. if (pickResult) {
  24088. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  24089. if (this.onPointerDown) {
  24090. this.onPointerDown(evt, pickResult, type);
  24091. }
  24092. if (this.onPointerObservable.hasObservers()) {
  24093. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24094. this.onPointerObservable.notifyObservers(pi, type);
  24095. }
  24096. }
  24097. return this;
  24098. };
  24099. /**
  24100. * Use this method to simulate a pointer up on a mesh
  24101. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24102. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24103. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24104. * @returns the current scene
  24105. */
  24106. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  24107. var evt = new PointerEvent("pointerup", pointerEventInit);
  24108. var clickInfo = new ClickInfo();
  24109. clickInfo.singleClick = true;
  24110. clickInfo.ignore = true;
  24111. return this._processPointerUp(pickResult, evt, clickInfo);
  24112. };
  24113. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  24114. if (pickResult && pickResult && pickResult.pickedMesh) {
  24115. this._pickedUpMesh = pickResult.pickedMesh;
  24116. if (this._pickedDownMesh === this._pickedUpMesh) {
  24117. if (this.onPointerPick) {
  24118. this.onPointerPick(evt, pickResult);
  24119. }
  24120. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  24121. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  24122. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  24123. this.onPointerObservable.notifyObservers(pi, type_1);
  24124. }
  24125. }
  24126. if (pickResult.pickedMesh.actionManager) {
  24127. if (clickInfo.ignore) {
  24128. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24129. }
  24130. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  24131. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24132. }
  24133. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  24134. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24135. }
  24136. }
  24137. }
  24138. if (this._pickedDownMesh &&
  24139. this._pickedDownMesh.actionManager &&
  24140. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  24141. this._pickedDownMesh !== this._pickedUpMesh) {
  24142. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  24143. }
  24144. var type = BABYLON.PointerEventTypes.POINTERUP;
  24145. if (this.onPointerObservable.hasObservers()) {
  24146. if (!clickInfo.ignore) {
  24147. if (!clickInfo.hasSwiped) {
  24148. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  24149. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  24150. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  24151. this.onPointerObservable.notifyObservers(pi, type_2);
  24152. }
  24153. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  24154. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  24155. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  24156. this.onPointerObservable.notifyObservers(pi, type_3);
  24157. }
  24158. }
  24159. }
  24160. else {
  24161. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24162. this.onPointerObservable.notifyObservers(pi, type);
  24163. }
  24164. }
  24165. if (this.onPointerUp) {
  24166. this.onPointerUp(evt, pickResult, type);
  24167. }
  24168. return this;
  24169. };
  24170. /**
  24171. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  24172. * @param attachUp defines if you want to attach events to pointerup
  24173. * @param attachDown defines if you want to attach events to pointerdown
  24174. * @param attachMove defines if you want to attach events to pointermove
  24175. */
  24176. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  24177. var _this = this;
  24178. if (attachUp === void 0) { attachUp = true; }
  24179. if (attachDown === void 0) { attachDown = true; }
  24180. if (attachMove === void 0) { attachMove = true; }
  24181. this._initActionManager = function (act, clickInfo) {
  24182. if (!_this._meshPickProceed) {
  24183. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  24184. _this._currentPickResult = pickResult;
  24185. if (pickResult) {
  24186. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  24187. }
  24188. _this._meshPickProceed = true;
  24189. }
  24190. return act;
  24191. };
  24192. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  24193. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  24194. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  24195. btn !== _this._previousButtonPressed) {
  24196. _this._doubleClickOccured = false;
  24197. clickInfo.singleClick = true;
  24198. clickInfo.ignore = false;
  24199. cb(clickInfo, _this._currentPickResult);
  24200. }
  24201. };
  24202. this._initClickEvent = function (obs1, obs2, evt, cb) {
  24203. var clickInfo = new ClickInfo();
  24204. _this._currentPickResult = null;
  24205. var act = null;
  24206. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  24207. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  24208. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  24209. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  24210. act = _this._initActionManager(act, clickInfo);
  24211. if (act)
  24212. checkPicking = act.hasPickTriggers;
  24213. }
  24214. if (checkPicking) {
  24215. var btn = evt.button;
  24216. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  24217. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  24218. if (!clickInfo.hasSwiped) {
  24219. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  24220. if (!checkSingleClickImmediately) {
  24221. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  24222. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  24223. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  24224. act = _this._initActionManager(act, clickInfo);
  24225. if (act)
  24226. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  24227. }
  24228. }
  24229. if (checkSingleClickImmediately) {
  24230. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  24231. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  24232. btn !== _this._previousButtonPressed) {
  24233. clickInfo.singleClick = true;
  24234. cb(clickInfo, _this._currentPickResult);
  24235. }
  24236. }
  24237. else {
  24238. // wait that no double click has been raised during the double click delay
  24239. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  24240. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  24241. }
  24242. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  24243. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  24244. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  24245. act = _this._initActionManager(act, clickInfo);
  24246. if (act)
  24247. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  24248. }
  24249. if (checkDoubleClick) {
  24250. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  24251. if (btn === _this._previousButtonPressed &&
  24252. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  24253. !_this._doubleClickOccured) {
  24254. // pointer has not moved for 2 clicks, it's a double click
  24255. if (!clickInfo.hasSwiped &&
  24256. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  24257. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  24258. _this._previousStartingPointerTime = 0;
  24259. _this._doubleClickOccured = true;
  24260. clickInfo.doubleClick = true;
  24261. clickInfo.ignore = false;
  24262. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  24263. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  24264. }
  24265. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  24266. cb(clickInfo, _this._currentPickResult);
  24267. }
  24268. else {
  24269. _this._doubleClickOccured = false;
  24270. _this._previousStartingPointerTime = _this._startingPointerTime;
  24271. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  24272. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  24273. _this._previousButtonPressed = btn;
  24274. if (Scene.ExclusiveDoubleClickMode) {
  24275. if (_this._previousDelayedSimpleClickTimeout) {
  24276. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  24277. }
  24278. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  24279. cb(clickInfo, _this._previousPickResult);
  24280. }
  24281. else {
  24282. cb(clickInfo, _this._currentPickResult);
  24283. }
  24284. }
  24285. }
  24286. else {
  24287. _this._doubleClickOccured = false;
  24288. _this._previousStartingPointerTime = _this._startingPointerTime;
  24289. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  24290. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  24291. _this._previousButtonPressed = btn;
  24292. }
  24293. }
  24294. }
  24295. }
  24296. clickInfo.ignore = true;
  24297. cb(clickInfo, _this._currentPickResult);
  24298. };
  24299. this._spritePredicate = function (sprite) {
  24300. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  24301. };
  24302. this._onPointerMove = function (evt) {
  24303. _this._updatePointerPosition(evt);
  24304. // PreObservable support
  24305. if (_this.onPrePointerObservable.hasObservers()) {
  24306. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24307. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24308. _this.onPrePointerObservable.notifyObservers(pi, type);
  24309. if (pi.skipOnPointerObservable) {
  24310. return;
  24311. }
  24312. }
  24313. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  24314. return;
  24315. }
  24316. if (!_this.pointerMovePredicate) {
  24317. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  24318. }
  24319. // Meshes
  24320. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  24321. _this._processPointerMove(pickResult, evt);
  24322. };
  24323. this._onPointerDown = function (evt) {
  24324. _this._totalPointersPressed++;
  24325. _this._pickedDownMesh = null;
  24326. _this._meshPickProceed = false;
  24327. _this._updatePointerPosition(evt);
  24328. if (_this.preventDefaultOnPointerDown && canvas) {
  24329. evt.preventDefault();
  24330. canvas.focus();
  24331. }
  24332. // PreObservable support
  24333. if (_this.onPrePointerObservable.hasObservers()) {
  24334. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  24335. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24336. _this.onPrePointerObservable.notifyObservers(pi, type);
  24337. if (pi.skipOnPointerObservable) {
  24338. return;
  24339. }
  24340. }
  24341. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  24342. return;
  24343. }
  24344. _this._startingPointerPosition.x = _this._pointerX;
  24345. _this._startingPointerPosition.y = _this._pointerY;
  24346. _this._startingPointerTime = new Date().getTime();
  24347. if (!_this.pointerDownPredicate) {
  24348. _this.pointerDownPredicate = function (mesh) {
  24349. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  24350. };
  24351. }
  24352. // Meshes
  24353. _this._pickedDownMesh = null;
  24354. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  24355. _this._processPointerDown(pickResult, evt);
  24356. // Sprites
  24357. _this._pickedDownSprite = null;
  24358. if (_this.spriteManagers.length > 0) {
  24359. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  24360. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24361. if (pickResult.pickedSprite.actionManager) {
  24362. _this._pickedDownSprite = pickResult.pickedSprite;
  24363. switch (evt.button) {
  24364. case 0:
  24365. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  24366. break;
  24367. case 1:
  24368. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  24369. break;
  24370. case 2:
  24371. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  24372. break;
  24373. }
  24374. if (pickResult.pickedSprite.actionManager) {
  24375. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  24376. }
  24377. }
  24378. }
  24379. }
  24380. };
  24381. this._onPointerUp = function (evt) {
  24382. if (_this._totalPointersPressed === 0) {
  24383. return; // So we need to test it the pointer down was pressed before.
  24384. }
  24385. _this._totalPointersPressed--;
  24386. _this._pickedUpMesh = null;
  24387. _this._meshPickProceed = false;
  24388. _this._updatePointerPosition(evt);
  24389. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  24390. // PreObservable support
  24391. if (_this.onPrePointerObservable.hasObservers()) {
  24392. if (!clickInfo.ignore) {
  24393. if (!clickInfo.hasSwiped) {
  24394. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  24395. var type = BABYLON.PointerEventTypes.POINTERTAP;
  24396. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24397. _this.onPrePointerObservable.notifyObservers(pi, type);
  24398. if (pi.skipOnPointerObservable) {
  24399. return;
  24400. }
  24401. }
  24402. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  24403. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  24404. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24405. _this.onPrePointerObservable.notifyObservers(pi, type);
  24406. if (pi.skipOnPointerObservable) {
  24407. return;
  24408. }
  24409. }
  24410. }
  24411. }
  24412. else {
  24413. var type = BABYLON.PointerEventTypes.POINTERUP;
  24414. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24415. _this.onPrePointerObservable.notifyObservers(pi, type);
  24416. if (pi.skipOnPointerObservable) {
  24417. return;
  24418. }
  24419. }
  24420. }
  24421. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  24422. return;
  24423. }
  24424. if (!_this.pointerUpPredicate) {
  24425. _this.pointerUpPredicate = function (mesh) {
  24426. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  24427. };
  24428. }
  24429. // Meshes
  24430. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  24431. _this._initActionManager(null, clickInfo);
  24432. }
  24433. if (!pickResult) {
  24434. pickResult = _this._currentPickResult;
  24435. }
  24436. _this._processPointerUp(pickResult, evt, clickInfo);
  24437. // Sprites
  24438. if (_this.spriteManagers.length > 0) {
  24439. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  24440. if (spritePickResult) {
  24441. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  24442. if (spritePickResult.pickedSprite.actionManager) {
  24443. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  24444. if (spritePickResult.pickedSprite.actionManager) {
  24445. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  24446. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  24447. }
  24448. }
  24449. }
  24450. }
  24451. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  24452. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  24453. }
  24454. }
  24455. }
  24456. _this._previousPickResult = _this._currentPickResult;
  24457. });
  24458. };
  24459. this._onKeyDown = function (evt) {
  24460. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  24461. if (_this.onPreKeyboardObservable.hasObservers()) {
  24462. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  24463. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  24464. if (pi.skipOnPointerObservable) {
  24465. return;
  24466. }
  24467. }
  24468. if (_this.onKeyboardObservable.hasObservers()) {
  24469. var pi = new BABYLON.KeyboardInfo(type, evt);
  24470. _this.onKeyboardObservable.notifyObservers(pi, type);
  24471. }
  24472. if (_this.actionManager) {
  24473. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  24474. }
  24475. };
  24476. this._onKeyUp = function (evt) {
  24477. var type = BABYLON.KeyboardEventTypes.KEYUP;
  24478. if (_this.onPreKeyboardObservable.hasObservers()) {
  24479. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  24480. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  24481. if (pi.skipOnPointerObservable) {
  24482. return;
  24483. }
  24484. }
  24485. if (_this.onKeyboardObservable.hasObservers()) {
  24486. var pi = new BABYLON.KeyboardInfo(type, evt);
  24487. _this.onKeyboardObservable.notifyObservers(pi, type);
  24488. }
  24489. if (_this.actionManager) {
  24490. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  24491. }
  24492. };
  24493. var engine = this.getEngine();
  24494. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  24495. if (!canvas) {
  24496. return;
  24497. }
  24498. canvas.addEventListener("keydown", _this._onKeyDown, false);
  24499. canvas.addEventListener("keyup", _this._onKeyUp, false);
  24500. });
  24501. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  24502. if (!canvas) {
  24503. return;
  24504. }
  24505. canvas.removeEventListener("keydown", _this._onKeyDown);
  24506. canvas.removeEventListener("keyup", _this._onKeyUp);
  24507. });
  24508. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  24509. var canvas = this._engine.getRenderingCanvas();
  24510. if (!canvas) {
  24511. return;
  24512. }
  24513. if (attachMove) {
  24514. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  24515. // Wheel
  24516. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  24517. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  24518. }
  24519. if (attachDown) {
  24520. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  24521. }
  24522. if (attachUp) {
  24523. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  24524. }
  24525. canvas.tabIndex = 1;
  24526. };
  24527. /** Detaches all event handlers*/
  24528. Scene.prototype.detachControl = function () {
  24529. var engine = this.getEngine();
  24530. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  24531. var canvas = engine.getRenderingCanvas();
  24532. if (!canvas) {
  24533. return;
  24534. }
  24535. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  24536. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  24537. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  24538. if (this._onCanvasBlurObserver) {
  24539. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  24540. }
  24541. if (this._onCanvasFocusObserver) {
  24542. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  24543. }
  24544. // Wheel
  24545. canvas.removeEventListener('mousewheel', this._onPointerMove);
  24546. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  24547. // Keyboard
  24548. canvas.removeEventListener("keydown", this._onKeyDown);
  24549. canvas.removeEventListener("keyup", this._onKeyUp);
  24550. // Observables
  24551. this.onKeyboardObservable.clear();
  24552. this.onPreKeyboardObservable.clear();
  24553. this.onPointerObservable.clear();
  24554. this.onPrePointerObservable.clear();
  24555. };
  24556. /**
  24557. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  24558. * Delay loaded resources are not taking in account
  24559. * @return true if all required resources are ready
  24560. */
  24561. Scene.prototype.isReady = function () {
  24562. if (this._isDisposed) {
  24563. return false;
  24564. }
  24565. if (this._pendingData.length > 0) {
  24566. return false;
  24567. }
  24568. var index;
  24569. var engine = this.getEngine();
  24570. // Geometries
  24571. for (index = 0; index < this._geometries.length; index++) {
  24572. var geometry = this._geometries[index];
  24573. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  24574. return false;
  24575. }
  24576. }
  24577. // Meshes
  24578. for (index = 0; index < this.meshes.length; index++) {
  24579. var mesh = this.meshes[index];
  24580. if (!mesh.isEnabled()) {
  24581. continue;
  24582. }
  24583. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  24584. continue;
  24585. }
  24586. if (!mesh.isReady(true)) {
  24587. return false;
  24588. }
  24589. // Effect layers
  24590. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  24591. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  24592. var layer = _a[_i];
  24593. if (!layer.hasMesh(mesh)) {
  24594. continue;
  24595. }
  24596. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  24597. var subMesh = _c[_b];
  24598. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  24599. return false;
  24600. }
  24601. }
  24602. }
  24603. }
  24604. // Post-processes
  24605. if (this.activeCameras && this.activeCameras.length > 0) {
  24606. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  24607. var camera = _e[_d];
  24608. if (!camera.isReady(true)) {
  24609. return false;
  24610. }
  24611. }
  24612. }
  24613. else if (this.activeCamera) {
  24614. if (!this.activeCamera.isReady(true)) {
  24615. return false;
  24616. }
  24617. }
  24618. // Particles
  24619. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  24620. var particleSystem = _g[_f];
  24621. if (!particleSystem.isReady()) {
  24622. return false;
  24623. }
  24624. }
  24625. return true;
  24626. };
  24627. /** Resets all cached information relative to material (including effect and visibility) */
  24628. Scene.prototype.resetCachedMaterial = function () {
  24629. this._cachedMaterial = null;
  24630. this._cachedEffect = null;
  24631. this._cachedVisibility = null;
  24632. };
  24633. /**
  24634. * Registers a function to be called before every frame render
  24635. * @param func defines the function to register
  24636. */
  24637. Scene.prototype.registerBeforeRender = function (func) {
  24638. this.onBeforeRenderObservable.add(func);
  24639. };
  24640. /**
  24641. * Unregisters a function called before every frame render
  24642. * @param func defines the function to unregister
  24643. */
  24644. Scene.prototype.unregisterBeforeRender = function (func) {
  24645. this.onBeforeRenderObservable.removeCallback(func);
  24646. };
  24647. /**
  24648. * Registers a function to be called after every frame render
  24649. * @param func defines the function to register
  24650. */
  24651. Scene.prototype.registerAfterRender = function (func) {
  24652. this.onAfterRenderObservable.add(func);
  24653. };
  24654. /**
  24655. * Unregisters a function called after every frame render
  24656. * @param func defines the function to unregister
  24657. */
  24658. Scene.prototype.unregisterAfterRender = function (func) {
  24659. this.onAfterRenderObservable.removeCallback(func);
  24660. };
  24661. Scene.prototype._executeOnceBeforeRender = function (func) {
  24662. var _this = this;
  24663. var execFunc = function () {
  24664. func();
  24665. setTimeout(function () {
  24666. _this.unregisterBeforeRender(execFunc);
  24667. });
  24668. };
  24669. this.registerBeforeRender(execFunc);
  24670. };
  24671. /**
  24672. * The provided function will run before render once and will be disposed afterwards.
  24673. * A timeout delay can be provided so that the function will be executed in N ms.
  24674. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  24675. * @param func The function to be executed.
  24676. * @param timeout optional delay in ms
  24677. */
  24678. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  24679. var _this = this;
  24680. if (timeout !== undefined) {
  24681. setTimeout(function () {
  24682. _this._executeOnceBeforeRender(func);
  24683. }, timeout);
  24684. }
  24685. else {
  24686. this._executeOnceBeforeRender(func);
  24687. }
  24688. };
  24689. /** @ignore */
  24690. Scene.prototype._addPendingData = function (data) {
  24691. this._pendingData.push(data);
  24692. };
  24693. /** @ignore */
  24694. Scene.prototype._removePendingData = function (data) {
  24695. var wasLoading = this.isLoading;
  24696. var index = this._pendingData.indexOf(data);
  24697. if (index !== -1) {
  24698. this._pendingData.splice(index, 1);
  24699. }
  24700. if (wasLoading && !this.isLoading) {
  24701. this.onDataLoadedObservable.notifyObservers(this);
  24702. }
  24703. };
  24704. /**
  24705. * Returns the number of items waiting to be loaded
  24706. * @returns the number of items waiting to be loaded
  24707. */
  24708. Scene.prototype.getWaitingItemsCount = function () {
  24709. return this._pendingData.length;
  24710. };
  24711. Object.defineProperty(Scene.prototype, "isLoading", {
  24712. /**
  24713. * Returns a boolean indicating if the scene is still loading data
  24714. */
  24715. get: function () {
  24716. return this._pendingData.length > 0;
  24717. },
  24718. enumerable: true,
  24719. configurable: true
  24720. });
  24721. /**
  24722. * Registers a function to be executed when the scene is ready
  24723. * @param {Function} func - the function to be executed
  24724. */
  24725. Scene.prototype.executeWhenReady = function (func) {
  24726. var _this = this;
  24727. this.onReadyObservable.add(func);
  24728. if (this._executeWhenReadyTimeoutId !== -1) {
  24729. return;
  24730. }
  24731. this._executeWhenReadyTimeoutId = setTimeout(function () {
  24732. _this._checkIsReady();
  24733. }, 150);
  24734. };
  24735. /**
  24736. * Returns a promise that resolves when the scene is ready
  24737. * @returns A promise that resolves when the scene is ready
  24738. */
  24739. Scene.prototype.whenReadyAsync = function () {
  24740. var _this = this;
  24741. return new Promise(function (resolve) {
  24742. _this.executeWhenReady(function () {
  24743. resolve();
  24744. });
  24745. });
  24746. };
  24747. /** @ignore */
  24748. Scene.prototype._checkIsReady = function () {
  24749. var _this = this;
  24750. if (this.isReady()) {
  24751. this.onReadyObservable.notifyObservers(this);
  24752. this.onReadyObservable.clear();
  24753. this._executeWhenReadyTimeoutId = -1;
  24754. return;
  24755. }
  24756. this._executeWhenReadyTimeoutId = setTimeout(function () {
  24757. _this._checkIsReady();
  24758. }, 150);
  24759. };
  24760. // Animations
  24761. /**
  24762. * Will start the animation sequence of a given target
  24763. * @param target defines the target
  24764. * @param from defines from which frame should animation start
  24765. * @param to defines until which frame should animation run.
  24766. * @param weight defines the weight to apply to the animation (1.0 by default)
  24767. * @param loop defines if the animation loops
  24768. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  24769. * @param onAnimationEnd defines the function to be executed when the animation ends
  24770. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  24771. * @returns the animatable object created for this animation
  24772. */
  24773. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  24774. if (weight === void 0) { weight = 1.0; }
  24775. if (speedRatio === void 0) { speedRatio = 1.0; }
  24776. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  24777. returnedAnimatable.weight = weight;
  24778. return returnedAnimatable;
  24779. };
  24780. /**
  24781. * Will start the animation sequence of a given target
  24782. * @param target defines the target
  24783. * @param from defines from which frame should animation start
  24784. * @param to defines until which frame should animation run.
  24785. * @param loop defines if the animation loops
  24786. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  24787. * @param onAnimationEnd defines the function to be executed when the animation ends
  24788. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  24789. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  24790. * @returns the animatable object created for this animation
  24791. */
  24792. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  24793. if (speedRatio === void 0) { speedRatio = 1.0; }
  24794. if (stopCurrent === void 0) { stopCurrent = true; }
  24795. if (from > to && speedRatio > 0) {
  24796. speedRatio *= -1;
  24797. }
  24798. if (stopCurrent) {
  24799. this.stopAnimation(target);
  24800. }
  24801. if (!animatable) {
  24802. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  24803. }
  24804. // Local animations
  24805. if (target.animations) {
  24806. animatable.appendAnimations(target, target.animations);
  24807. }
  24808. // Children animations
  24809. if (target.getAnimatables) {
  24810. var animatables = target.getAnimatables();
  24811. for (var index = 0; index < animatables.length; index++) {
  24812. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  24813. }
  24814. }
  24815. animatable.reset();
  24816. return animatable;
  24817. };
  24818. /**
  24819. * Begin a new animation on a given node
  24820. * @param target defines the target where the animation will take place
  24821. * @param animations defines the list of animations to start
  24822. * @param from defines the initial value
  24823. * @param to defines the final value
  24824. * @param loop defines if you want animation to loop (off by default)
  24825. * @param speedRatio defines the speed ratio to apply to all animations
  24826. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  24827. * @returns the list of created animatables
  24828. */
  24829. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  24830. if (speedRatio === undefined) {
  24831. speedRatio = 1.0;
  24832. }
  24833. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  24834. return animatable;
  24835. };
  24836. /**
  24837. * Begin a new animation on a given node and its hierarchy
  24838. * @param target defines the root node where the animation will take place
  24839. * @param directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  24840. * @param animations defines the list of animations to start
  24841. * @param from defines the initial value
  24842. * @param to defines the final value
  24843. * @param loop defines if you want animation to loop (off by default)
  24844. * @param speedRatio defines the speed ratio to apply to all animations
  24845. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  24846. * @returns the list of animatables created for all nodes
  24847. */
  24848. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  24849. var children = target.getDescendants(directDescendantsOnly);
  24850. var result = [];
  24851. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  24852. var child = children_1[_i];
  24853. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  24854. }
  24855. return result;
  24856. };
  24857. /**
  24858. * Gets the animatable associated with a specific target
  24859. * @param target defines the target of the animatable
  24860. * @returns the required animatable if found
  24861. */
  24862. Scene.prototype.getAnimatableByTarget = function (target) {
  24863. for (var index = 0; index < this._activeAnimatables.length; index++) {
  24864. if (this._activeAnimatables[index].target === target) {
  24865. return this._activeAnimatables[index];
  24866. }
  24867. }
  24868. return null;
  24869. };
  24870. /**
  24871. * Gets all animatables associated with a given target
  24872. * @param target defines the target to look animatables for
  24873. * @returns an array of Animatables
  24874. */
  24875. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  24876. var result = [];
  24877. for (var index = 0; index < this._activeAnimatables.length; index++) {
  24878. if (this._activeAnimatables[index].target === target) {
  24879. result.push(this._activeAnimatables[index]);
  24880. }
  24881. }
  24882. return result;
  24883. };
  24884. Object.defineProperty(Scene.prototype, "animatables", {
  24885. /**
  24886. * Gets all animatable attached to the scene
  24887. */
  24888. get: function () {
  24889. return this._activeAnimatables;
  24890. },
  24891. enumerable: true,
  24892. configurable: true
  24893. });
  24894. /**
  24895. * Will stop the animation of the given target
  24896. * @param target - the target
  24897. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  24898. */
  24899. Scene.prototype.stopAnimation = function (target, animationName) {
  24900. var animatables = this.getAllAnimatablesByTarget(target);
  24901. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  24902. var animatable = animatables_1[_i];
  24903. animatable.stop(animationName);
  24904. }
  24905. };
  24906. /**
  24907. * Stops and removes all animations that have been applied to the scene
  24908. */
  24909. Scene.prototype.stopAllAnimations = function () {
  24910. if (this._activeAnimatables) {
  24911. for (var i = 0; i < this._activeAnimatables.length; i++) {
  24912. this._activeAnimatables[i].stop();
  24913. }
  24914. this._activeAnimatables = [];
  24915. }
  24916. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  24917. var group = _a[_i];
  24918. group.stop();
  24919. }
  24920. };
  24921. Scene.prototype._animate = function () {
  24922. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  24923. return;
  24924. }
  24925. // Getting time
  24926. var now = BABYLON.Tools.Now;
  24927. if (!this._animationTimeLast) {
  24928. if (this._pendingData.length > 0) {
  24929. return;
  24930. }
  24931. this._animationTimeLast = now;
  24932. }
  24933. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  24934. this._animationTime += deltaTime;
  24935. this._animationTimeLast = now;
  24936. for (var index = 0; index < this._activeAnimatables.length; index++) {
  24937. this._activeAnimatables[index]._animate(this._animationTime);
  24938. }
  24939. // Late animation bindings
  24940. this._processLateAnimationBindings();
  24941. };
  24942. /** @ignore */
  24943. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation) {
  24944. var target = runtimeAnimation.target;
  24945. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  24946. if (!target._lateAnimationHolders) {
  24947. target._lateAnimationHolders = {};
  24948. }
  24949. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  24950. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  24951. totalWeight: 0,
  24952. animations: []
  24953. };
  24954. }
  24955. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  24956. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  24957. };
  24958. Scene.prototype._processLateAnimationBindings = function () {
  24959. if (!this._registeredForLateAnimationBindings.length) {
  24960. return;
  24961. }
  24962. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  24963. var target = this._registeredForLateAnimationBindings.data[index];
  24964. for (var path in target._lateAnimationHolders) {
  24965. var holder = target._lateAnimationHolders[path];
  24966. // Sanity check
  24967. if (!holder.animations[0].originalValue.scaleAndAddToRef) {
  24968. continue;
  24969. }
  24970. var normalizer = 1.0;
  24971. var finalValue = void 0;
  24972. if (holder.totalWeight < 1.0) {
  24973. // We need to mix the original value in
  24974. var originalValue = holder.animations[0].originalValue;
  24975. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  24976. }
  24977. else {
  24978. // We need to normalize the weights
  24979. normalizer = holder.totalWeight;
  24980. }
  24981. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  24982. var runtimeAnimation = holder.animations[animIndex];
  24983. if (finalValue) {
  24984. runtimeAnimation.currentValue.scaleAndAddToRef(runtimeAnimation.weight / normalizer, finalValue);
  24985. }
  24986. else {
  24987. finalValue = runtimeAnimation.currentValue.scale(runtimeAnimation.weight / normalizer);
  24988. }
  24989. }
  24990. runtimeAnimation.target[path] = finalValue;
  24991. }
  24992. target._lateAnimationHolders = {};
  24993. }
  24994. this._registeredForLateAnimationBindings.reset();
  24995. };
  24996. // Matrix
  24997. /** @ignore */
  24998. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  24999. this._useAlternateCameraConfiguration = active;
  25000. };
  25001. /**
  25002. * Gets the current view matrix
  25003. * @returns a Matrix
  25004. */
  25005. Scene.prototype.getViewMatrix = function () {
  25006. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  25007. };
  25008. /**
  25009. * Gets the current projection matrix
  25010. * @returns a Matrix
  25011. */
  25012. Scene.prototype.getProjectionMatrix = function () {
  25013. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  25014. };
  25015. /**
  25016. * Gets the current transform matrix
  25017. * @returns a Matrix made of View * Projection
  25018. */
  25019. Scene.prototype.getTransformMatrix = function () {
  25020. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  25021. };
  25022. /**
  25023. * Sets the current transform matrix
  25024. * @param view defines the View matrix to use
  25025. * @param projection defines the Projection matrix to use
  25026. */
  25027. Scene.prototype.setTransformMatrix = function (view, projection) {
  25028. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  25029. return;
  25030. }
  25031. this._viewUpdateFlag = view.updateFlag;
  25032. this._projectionUpdateFlag = projection.updateFlag;
  25033. this._viewMatrix = view;
  25034. this._projectionMatrix = projection;
  25035. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  25036. // Update frustum
  25037. if (!this._frustumPlanes) {
  25038. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  25039. }
  25040. else {
  25041. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  25042. }
  25043. if (this.activeCamera && this.activeCamera._alternateCamera) {
  25044. var otherCamera = this.activeCamera._alternateCamera;
  25045. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  25046. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  25047. }
  25048. if (this._sceneUbo.useUbo) {
  25049. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  25050. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  25051. this._sceneUbo.update();
  25052. }
  25053. };
  25054. /** @ignore */
  25055. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  25056. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  25057. return;
  25058. }
  25059. this._alternateViewUpdateFlag = view.updateFlag;
  25060. this._alternateProjectionUpdateFlag = projection.updateFlag;
  25061. this._alternateViewMatrix = view;
  25062. this._alternateProjectionMatrix = projection;
  25063. if (!this._alternateTransformMatrix) {
  25064. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  25065. }
  25066. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  25067. if (!this._alternateSceneUbo) {
  25068. this._createAlternateUbo();
  25069. }
  25070. if (this._alternateSceneUbo.useUbo) {
  25071. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  25072. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  25073. this._alternateSceneUbo.update();
  25074. }
  25075. };
  25076. /**
  25077. * Gets the uniform buffer used to store scene data
  25078. * @returns a UniformBuffer
  25079. */
  25080. Scene.prototype.getSceneUniformBuffer = function () {
  25081. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  25082. };
  25083. /**
  25084. * Gets an unique (relatively to the current scene) Id
  25085. * @returns an unique number for the scene
  25086. */
  25087. Scene.prototype.getUniqueId = function () {
  25088. var result = Scene._uniqueIdCounter;
  25089. Scene._uniqueIdCounter++;
  25090. return result;
  25091. };
  25092. /**
  25093. * Add a mesh to the list of scene's meshes
  25094. * @param newMesh defines the mesh to add
  25095. */
  25096. Scene.prototype.addMesh = function (newMesh) {
  25097. this.meshes.push(newMesh);
  25098. //notify the collision coordinator
  25099. if (this.collisionCoordinator) {
  25100. this.collisionCoordinator.onMeshAdded(newMesh);
  25101. }
  25102. newMesh._resyncLightSources();
  25103. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  25104. };
  25105. /**
  25106. * Remove a mesh for the list of scene's meshes
  25107. * @param toRemove defines the mesh to remove
  25108. * @returns the index where the mesh was in the mesh list
  25109. */
  25110. Scene.prototype.removeMesh = function (toRemove) {
  25111. var index = this.meshes.indexOf(toRemove);
  25112. if (index !== -1) {
  25113. // Remove from the scene if mesh found
  25114. this.meshes.splice(index, 1);
  25115. }
  25116. this.onMeshRemovedObservable.notifyObservers(toRemove);
  25117. return index;
  25118. };
  25119. /**
  25120. * Add a transform node to the list of scene's transform nodes
  25121. * @param newTransformNode defines the transform node to add
  25122. */
  25123. Scene.prototype.addTransformNode = function (newTransformNode) {
  25124. this.transformNodes.push(newTransformNode);
  25125. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  25126. };
  25127. /**
  25128. * Remove a transform node for the list of scene's transform nodes
  25129. * @param toRemove defines the transform node to remove
  25130. * @returns the index where the transform node was in the transform node list
  25131. */
  25132. Scene.prototype.removeTransformNode = function (toRemove) {
  25133. var index = this.transformNodes.indexOf(toRemove);
  25134. if (index !== -1) {
  25135. // Remove from the scene if found
  25136. this.transformNodes.splice(index, 1);
  25137. }
  25138. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  25139. return index;
  25140. };
  25141. /**
  25142. * Remove a skeleton for the list of scene's skeletons
  25143. * @param toRemove defines the skeleton to remove
  25144. * @returns the index where the skeleton was in the skeleton list
  25145. */
  25146. Scene.prototype.removeSkeleton = function (toRemove) {
  25147. var index = this.skeletons.indexOf(toRemove);
  25148. if (index !== -1) {
  25149. // Remove from the scene if found
  25150. this.skeletons.splice(index, 1);
  25151. }
  25152. return index;
  25153. };
  25154. /**
  25155. * Remove a morph target for the list of scene's morph targets
  25156. * @param toRemove defines the morph target to remove
  25157. * @returns the index where the morph target was in the morph target list
  25158. */
  25159. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  25160. var index = this.morphTargetManagers.indexOf(toRemove);
  25161. if (index !== -1) {
  25162. // Remove from the scene if found
  25163. this.morphTargetManagers.splice(index, 1);
  25164. }
  25165. return index;
  25166. };
  25167. /**
  25168. * Remove a light for the list of scene's lights
  25169. * @param toRemove defines the light to remove
  25170. * @returns the index where the light was in the light list
  25171. */
  25172. Scene.prototype.removeLight = function (toRemove) {
  25173. var index = this.lights.indexOf(toRemove);
  25174. if (index !== -1) {
  25175. // Remove from meshes
  25176. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  25177. var mesh = _a[_i];
  25178. mesh._removeLightSource(toRemove);
  25179. }
  25180. // Remove from the scene if mesh found
  25181. this.lights.splice(index, 1);
  25182. this.sortLightsByPriority();
  25183. }
  25184. this.onLightRemovedObservable.notifyObservers(toRemove);
  25185. return index;
  25186. };
  25187. /**
  25188. * Remove a camera for the list of scene's cameras
  25189. * @param toRemove defines the camera to remove
  25190. * @returns the index where the camera was in the camera list
  25191. */
  25192. Scene.prototype.removeCamera = function (toRemove) {
  25193. var index = this.cameras.indexOf(toRemove);
  25194. if (index !== -1) {
  25195. // Remove from the scene if mesh found
  25196. this.cameras.splice(index, 1);
  25197. }
  25198. // Remove from activeCameras
  25199. var index2 = this.activeCameras.indexOf(toRemove);
  25200. if (index2 !== -1) {
  25201. // Remove from the scene if mesh found
  25202. this.activeCameras.splice(index2, 1);
  25203. }
  25204. // Reset the activeCamera
  25205. if (this.activeCamera === toRemove) {
  25206. if (this.cameras.length > 0) {
  25207. this.activeCamera = this.cameras[0];
  25208. }
  25209. else {
  25210. this.activeCamera = null;
  25211. }
  25212. }
  25213. this.onCameraRemovedObservable.notifyObservers(toRemove);
  25214. return index;
  25215. };
  25216. /**
  25217. * Remove a particle system for the list of scene's particle systems
  25218. * @param toRemove defines the particle system to remove
  25219. * @returns the index where the particle system was in the particle system list
  25220. */
  25221. Scene.prototype.removeParticleSystem = function (toRemove) {
  25222. var index = this.particleSystems.indexOf(toRemove);
  25223. if (index !== -1) {
  25224. this.particleSystems.splice(index, 1);
  25225. }
  25226. return index;
  25227. };
  25228. /**
  25229. * Remove a animation for the list of scene's animations
  25230. * @param toRemove defines the animation to remove
  25231. * @returns the index where the animation was in the animation list
  25232. */
  25233. Scene.prototype.removeAnimation = function (toRemove) {
  25234. var index = this.animations.indexOf(toRemove);
  25235. if (index !== -1) {
  25236. this.animations.splice(index, 1);
  25237. }
  25238. return index;
  25239. };
  25240. /**
  25241. * Removes the given animation group from this scene.
  25242. * @param toRemove The animation group to remove
  25243. * @returns The index of the removed animation group
  25244. */
  25245. Scene.prototype.removeAnimationGroup = function (toRemove) {
  25246. var index = this.animationGroups.indexOf(toRemove);
  25247. if (index !== -1) {
  25248. this.animationGroups.splice(index, 1);
  25249. }
  25250. return index;
  25251. };
  25252. /**
  25253. * Removes the given multi-material from this scene.
  25254. * @param toRemove The multi-material to remove
  25255. * @returns The index of the removed multi-material
  25256. */
  25257. Scene.prototype.removeMultiMaterial = function (toRemove) {
  25258. var index = this.multiMaterials.indexOf(toRemove);
  25259. if (index !== -1) {
  25260. this.multiMaterials.splice(index, 1);
  25261. }
  25262. return index;
  25263. };
  25264. /**
  25265. * Removes the given material from this scene.
  25266. * @param toRemove The material to remove
  25267. * @returns The index of the removed material
  25268. */
  25269. Scene.prototype.removeMaterial = function (toRemove) {
  25270. var index = this.materials.indexOf(toRemove);
  25271. if (index !== -1) {
  25272. this.materials.splice(index, 1);
  25273. }
  25274. return index;
  25275. };
  25276. /**
  25277. * Removes the given lens flare system from this scene.
  25278. * @param toRemove The lens flare system to remove
  25279. * @returns The index of the removed lens flare system
  25280. */
  25281. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  25282. var index = this.lensFlareSystems.indexOf(toRemove);
  25283. if (index !== -1) {
  25284. this.lensFlareSystems.splice(index, 1);
  25285. }
  25286. return index;
  25287. };
  25288. /**
  25289. * Removes the given action manager from this scene.
  25290. * @param toRemove The action manager to remove
  25291. * @returns The index of the removed action manager
  25292. */
  25293. Scene.prototype.removeActionManager = function (toRemove) {
  25294. var index = this._actionManagers.indexOf(toRemove);
  25295. if (index !== -1) {
  25296. this._actionManagers.splice(index, 1);
  25297. }
  25298. return index;
  25299. };
  25300. /**
  25301. * Removes the given texture from this scene.
  25302. * @param toRemove The texture to remove
  25303. * @returns The index of the removed texture
  25304. */
  25305. Scene.prototype.removeTexture = function (toRemove) {
  25306. var index = this.textures.indexOf(toRemove);
  25307. if (index !== -1) {
  25308. this.textures.splice(index, 1);
  25309. }
  25310. return index;
  25311. };
  25312. /**
  25313. * Adds the given light to this scene
  25314. * @param newLight The light to add
  25315. */
  25316. Scene.prototype.addLight = function (newLight) {
  25317. this.lights.push(newLight);
  25318. this.sortLightsByPriority();
  25319. // Add light to all meshes (To support if the light is removed and then readded)
  25320. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  25321. var mesh = _a[_i];
  25322. if (mesh._lightSources.indexOf(newLight) === -1) {
  25323. mesh._lightSources.push(newLight);
  25324. mesh._resyncLightSources();
  25325. }
  25326. }
  25327. this.onNewLightAddedObservable.notifyObservers(newLight);
  25328. };
  25329. /**
  25330. * Sorts the list list based on light priorities
  25331. */
  25332. Scene.prototype.sortLightsByPriority = function () {
  25333. if (this.requireLightSorting) {
  25334. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  25335. }
  25336. };
  25337. /**
  25338. * Adds the given camera to this scene
  25339. * @param newCamera The camera to add
  25340. */
  25341. Scene.prototype.addCamera = function (newCamera) {
  25342. this.cameras.push(newCamera);
  25343. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  25344. };
  25345. /**
  25346. * Adds the given skeleton to this scene
  25347. * @param newSkeleton The skeleton to add
  25348. */
  25349. Scene.prototype.addSkeleton = function (newSkeleton) {
  25350. this.skeletons.push(newSkeleton);
  25351. };
  25352. /**
  25353. * Adds the given particle system to this scene
  25354. * @param newParticleSystem The particle system to add
  25355. */
  25356. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  25357. this.particleSystems.push(newParticleSystem);
  25358. };
  25359. /**
  25360. * Adds the given animation to this scene
  25361. * @param newAnimation The animation to add
  25362. */
  25363. Scene.prototype.addAnimation = function (newAnimation) {
  25364. this.animations.push(newAnimation);
  25365. };
  25366. /**
  25367. * Adds the given animation group to this scene.
  25368. * @param newAnimationGroup The animation group to add
  25369. */
  25370. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  25371. this.animationGroups.push(newAnimationGroup);
  25372. };
  25373. /**
  25374. * Adds the given multi-material to this scene
  25375. * @param newMultiMaterial The multi-material to add
  25376. */
  25377. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  25378. this.multiMaterials.push(newMultiMaterial);
  25379. };
  25380. /**
  25381. * Adds the given material to this scene
  25382. * @param newMaterial The material to add
  25383. */
  25384. Scene.prototype.addMaterial = function (newMaterial) {
  25385. this.materials.push(newMaterial);
  25386. };
  25387. /**
  25388. * Adds the given morph target to this scene
  25389. * @param newMorphTargetManager The morph target to add
  25390. */
  25391. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  25392. this.morphTargetManagers.push(newMorphTargetManager);
  25393. };
  25394. /**
  25395. * Adds the given geometry to this scene
  25396. * @param newGeometry The geometry to add
  25397. */
  25398. Scene.prototype.addGeometry = function (newGeometry) {
  25399. this._geometries.push(newGeometry);
  25400. };
  25401. /**
  25402. * Adds the given lens flare system to this scene
  25403. * @param newLensFlareSystem The lens flare system to add
  25404. */
  25405. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  25406. this.lensFlareSystems.push(newLensFlareSystem);
  25407. };
  25408. /**
  25409. * Adds the given action manager to this scene
  25410. * @param newActionManager The action manager to add
  25411. */
  25412. Scene.prototype.addActionManager = function (newActionManager) {
  25413. this._actionManagers.push(newActionManager);
  25414. };
  25415. /**
  25416. * Adds the given texture to this scene.
  25417. * @param newTexture The texture to add
  25418. */
  25419. Scene.prototype.addTexture = function (newTexture) {
  25420. this.textures.push(newTexture);
  25421. };
  25422. /**
  25423. * Switch active camera
  25424. * @param newCamera defines the new active camera
  25425. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  25426. */
  25427. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  25428. if (attachControl === void 0) { attachControl = true; }
  25429. var canvas = this._engine.getRenderingCanvas();
  25430. if (!canvas) {
  25431. return;
  25432. }
  25433. if (this.activeCamera) {
  25434. this.activeCamera.detachControl(canvas);
  25435. }
  25436. this.activeCamera = newCamera;
  25437. if (attachControl) {
  25438. newCamera.attachControl(canvas);
  25439. }
  25440. };
  25441. /**
  25442. * sets the active camera of the scene using its ID
  25443. * @param id defines the camera's ID
  25444. * @return the new active camera or null if none found.
  25445. */
  25446. Scene.prototype.setActiveCameraByID = function (id) {
  25447. var camera = this.getCameraByID(id);
  25448. if (camera) {
  25449. this.activeCamera = camera;
  25450. return camera;
  25451. }
  25452. return null;
  25453. };
  25454. /**
  25455. * sets the active camera of the scene using its name
  25456. * @param name defines the camera's name
  25457. * @returns the new active camera or null if none found.
  25458. */
  25459. Scene.prototype.setActiveCameraByName = function (name) {
  25460. var camera = this.getCameraByName(name);
  25461. if (camera) {
  25462. this.activeCamera = camera;
  25463. return camera;
  25464. }
  25465. return null;
  25466. };
  25467. /**
  25468. * get an animation group using its name
  25469. * @param name defines the material's name
  25470. * @return the animation group or null if none found.
  25471. */
  25472. Scene.prototype.getAnimationGroupByName = function (name) {
  25473. for (var index = 0; index < this.animationGroups.length; index++) {
  25474. if (this.animationGroups[index].name === name) {
  25475. return this.animationGroups[index];
  25476. }
  25477. }
  25478. return null;
  25479. };
  25480. /**
  25481. * get a material using its id
  25482. * @param id defines the material's ID
  25483. * @return the material or null if none found.
  25484. */
  25485. Scene.prototype.getMaterialByID = function (id) {
  25486. for (var index = 0; index < this.materials.length; index++) {
  25487. if (this.materials[index].id === id) {
  25488. return this.materials[index];
  25489. }
  25490. }
  25491. return null;
  25492. };
  25493. /**
  25494. * Gets a material using its name
  25495. * @param name defines the material's name
  25496. * @return the material or null if none found.
  25497. */
  25498. Scene.prototype.getMaterialByName = function (name) {
  25499. for (var index = 0; index < this.materials.length; index++) {
  25500. if (this.materials[index].name === name) {
  25501. return this.materials[index];
  25502. }
  25503. }
  25504. return null;
  25505. };
  25506. /**
  25507. * Gets a lens flare system using its name
  25508. * @param name defines the name to look for
  25509. * @returns the lens flare system or null if not found
  25510. */
  25511. Scene.prototype.getLensFlareSystemByName = function (name) {
  25512. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  25513. if (this.lensFlareSystems[index].name === name) {
  25514. return this.lensFlareSystems[index];
  25515. }
  25516. }
  25517. return null;
  25518. };
  25519. /**
  25520. * Gets a lens flare system using its id
  25521. * @param id defines the id to look for
  25522. * @returns the lens flare system or null if not found
  25523. */
  25524. Scene.prototype.getLensFlareSystemByID = function (id) {
  25525. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  25526. if (this.lensFlareSystems[index].id === id) {
  25527. return this.lensFlareSystems[index];
  25528. }
  25529. }
  25530. return null;
  25531. };
  25532. /**
  25533. * Gets a camera using its id
  25534. * @param id defines the id to look for
  25535. * @returns the camera or null if not found
  25536. */
  25537. Scene.prototype.getCameraByID = function (id) {
  25538. for (var index = 0; index < this.cameras.length; index++) {
  25539. if (this.cameras[index].id === id) {
  25540. return this.cameras[index];
  25541. }
  25542. }
  25543. return null;
  25544. };
  25545. /**
  25546. * Gets a camera using its unique id
  25547. * @param uniqueId defines the unique id to look for
  25548. * @returns the camera or null if not found
  25549. */
  25550. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  25551. for (var index = 0; index < this.cameras.length; index++) {
  25552. if (this.cameras[index].uniqueId === uniqueId) {
  25553. return this.cameras[index];
  25554. }
  25555. }
  25556. return null;
  25557. };
  25558. /**
  25559. * Gets a camera using its name
  25560. * @param name defines the camera's name
  25561. * @return the camera or null if none found.
  25562. */
  25563. Scene.prototype.getCameraByName = function (name) {
  25564. for (var index = 0; index < this.cameras.length; index++) {
  25565. if (this.cameras[index].name === name) {
  25566. return this.cameras[index];
  25567. }
  25568. }
  25569. return null;
  25570. };
  25571. /**
  25572. * Gets a bone using its id
  25573. * @param id defines the bone's id
  25574. * @return the bone or null if not found
  25575. */
  25576. Scene.prototype.getBoneByID = function (id) {
  25577. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  25578. var skeleton = this.skeletons[skeletonIndex];
  25579. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  25580. if (skeleton.bones[boneIndex].id === id) {
  25581. return skeleton.bones[boneIndex];
  25582. }
  25583. }
  25584. }
  25585. return null;
  25586. };
  25587. /**
  25588. * Gets a bone using its id
  25589. * @param name defines the bone's name
  25590. * @return the bone or null if not found
  25591. */
  25592. Scene.prototype.getBoneByName = function (name) {
  25593. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  25594. var skeleton = this.skeletons[skeletonIndex];
  25595. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  25596. if (skeleton.bones[boneIndex].name === name) {
  25597. return skeleton.bones[boneIndex];
  25598. }
  25599. }
  25600. }
  25601. return null;
  25602. };
  25603. /**
  25604. * Gets a light node using its name
  25605. * @param name defines the the light's name
  25606. * @return the light or null if none found.
  25607. */
  25608. Scene.prototype.getLightByName = function (name) {
  25609. for (var index = 0; index < this.lights.length; index++) {
  25610. if (this.lights[index].name === name) {
  25611. return this.lights[index];
  25612. }
  25613. }
  25614. return null;
  25615. };
  25616. /**
  25617. * Gets a light node using its id
  25618. * @param id defines the light's id
  25619. * @return the light or null if none found.
  25620. */
  25621. Scene.prototype.getLightByID = function (id) {
  25622. for (var index = 0; index < this.lights.length; index++) {
  25623. if (this.lights[index].id === id) {
  25624. return this.lights[index];
  25625. }
  25626. }
  25627. return null;
  25628. };
  25629. /**
  25630. * Gets a light node using its scene-generated unique ID
  25631. * @param uniqueId defines the light's unique id
  25632. * @return the light or null if none found.
  25633. */
  25634. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  25635. for (var index = 0; index < this.lights.length; index++) {
  25636. if (this.lights[index].uniqueId === uniqueId) {
  25637. return this.lights[index];
  25638. }
  25639. }
  25640. return null;
  25641. };
  25642. /**
  25643. * Gets a particle system by id
  25644. * @param id defines the particle system id
  25645. * @return the corresponding system or null if none found
  25646. */
  25647. Scene.prototype.getParticleSystemByID = function (id) {
  25648. for (var index = 0; index < this.particleSystems.length; index++) {
  25649. if (this.particleSystems[index].id === id) {
  25650. return this.particleSystems[index];
  25651. }
  25652. }
  25653. return null;
  25654. };
  25655. /**
  25656. * Gets a geometry using its ID
  25657. * @param id defines the geometry's id
  25658. * @return the geometry or null if none found.
  25659. */
  25660. Scene.prototype.getGeometryByID = function (id) {
  25661. for (var index = 0; index < this._geometries.length; index++) {
  25662. if (this._geometries[index].id === id) {
  25663. return this._geometries[index];
  25664. }
  25665. }
  25666. return null;
  25667. };
  25668. /**
  25669. * Add a new geometry to this scene
  25670. * @param geometry defines the geometry to be added to the scene.
  25671. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  25672. * @return a boolean defining if the geometry was added or not
  25673. */
  25674. Scene.prototype.pushGeometry = function (geometry, force) {
  25675. if (!force && this.getGeometryByID(geometry.id)) {
  25676. return false;
  25677. }
  25678. this._geometries.push(geometry);
  25679. //notify the collision coordinator
  25680. if (this.collisionCoordinator) {
  25681. this.collisionCoordinator.onGeometryAdded(geometry);
  25682. }
  25683. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  25684. return true;
  25685. };
  25686. /**
  25687. * Removes an existing geometry
  25688. * @param geometry defines the geometry to be removed from the scene
  25689. * @return a boolean defining if the geometry was removed or not
  25690. */
  25691. Scene.prototype.removeGeometry = function (geometry) {
  25692. var index = this._geometries.indexOf(geometry);
  25693. if (index > -1) {
  25694. this._geometries.splice(index, 1);
  25695. //notify the collision coordinator
  25696. if (this.collisionCoordinator) {
  25697. this.collisionCoordinator.onGeometryDeleted(geometry);
  25698. }
  25699. this.onGeometryRemovedObservable.notifyObservers(geometry);
  25700. return true;
  25701. }
  25702. return false;
  25703. };
  25704. /**
  25705. * Gets the list of geometries attached to the scene
  25706. * @returns an array of Geometry
  25707. */
  25708. Scene.prototype.getGeometries = function () {
  25709. return this._geometries;
  25710. };
  25711. /**
  25712. * Gets the first added mesh found of a given ID
  25713. * @param id defines the id to search for
  25714. * @return the mesh found or null if not found at all
  25715. */
  25716. Scene.prototype.getMeshByID = function (id) {
  25717. for (var index = 0; index < this.meshes.length; index++) {
  25718. if (this.meshes[index].id === id) {
  25719. return this.meshes[index];
  25720. }
  25721. }
  25722. return null;
  25723. };
  25724. /**
  25725. * Gets a list of meshes using their id
  25726. * @param id defines the id to search for
  25727. * @returns a list of meshes
  25728. */
  25729. Scene.prototype.getMeshesByID = function (id) {
  25730. return this.meshes.filter(function (m) {
  25731. return m.id === id;
  25732. });
  25733. };
  25734. /**
  25735. * Gets the first added transform node found of a given ID
  25736. * @param id defines the id to search for
  25737. * @return the found transform node or null if not found at all.
  25738. */
  25739. Scene.prototype.getTransformNodeByID = function (id) {
  25740. for (var index = 0; index < this.transformNodes.length; index++) {
  25741. if (this.transformNodes[index].id === id) {
  25742. return this.transformNodes[index];
  25743. }
  25744. }
  25745. return null;
  25746. };
  25747. /**
  25748. * Gets a list of transform nodes using their id
  25749. * @param id defines the id to search for
  25750. * @returns a list of transform nodes
  25751. */
  25752. Scene.prototype.getTransformNodesByID = function (id) {
  25753. return this.transformNodes.filter(function (m) {
  25754. return m.id === id;
  25755. });
  25756. };
  25757. /**
  25758. * Gets a mesh with its auto-generated unique id
  25759. * @param uniqueId defines the unique id to search for
  25760. * @return the found mesh or null if not found at all.
  25761. */
  25762. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  25763. for (var index = 0; index < this.meshes.length; index++) {
  25764. if (this.meshes[index].uniqueId === uniqueId) {
  25765. return this.meshes[index];
  25766. }
  25767. }
  25768. return null;
  25769. };
  25770. /**
  25771. * Gets a the last added mesh using a given id
  25772. * @param id defines the id to search for
  25773. * @return the found mesh or null if not found at all.
  25774. */
  25775. Scene.prototype.getLastMeshByID = function (id) {
  25776. for (var index = this.meshes.length - 1; index >= 0; index--) {
  25777. if (this.meshes[index].id === id) {
  25778. return this.meshes[index];
  25779. }
  25780. }
  25781. return null;
  25782. };
  25783. /**
  25784. * Gets a the last added node (Mesh, Camera, Light) using a given id
  25785. * @param id defines the id to search for
  25786. * @return the found node or null if not found at all
  25787. */
  25788. Scene.prototype.getLastEntryByID = function (id) {
  25789. var index;
  25790. for (index = this.meshes.length - 1; index >= 0; index--) {
  25791. if (this.meshes[index].id === id) {
  25792. return this.meshes[index];
  25793. }
  25794. }
  25795. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  25796. if (this.transformNodes[index].id === id) {
  25797. return this.transformNodes[index];
  25798. }
  25799. }
  25800. for (index = this.cameras.length - 1; index >= 0; index--) {
  25801. if (this.cameras[index].id === id) {
  25802. return this.cameras[index];
  25803. }
  25804. }
  25805. for (index = this.lights.length - 1; index >= 0; index--) {
  25806. if (this.lights[index].id === id) {
  25807. return this.lights[index];
  25808. }
  25809. }
  25810. return null;
  25811. };
  25812. /**
  25813. * Gets a node (Mesh, Camera, Light) using a given id
  25814. * @param id defines the id to search for
  25815. * @return the found node or null if not found at all
  25816. */
  25817. Scene.prototype.getNodeByID = function (id) {
  25818. var mesh = this.getMeshByID(id);
  25819. if (mesh) {
  25820. return mesh;
  25821. }
  25822. var light = this.getLightByID(id);
  25823. if (light) {
  25824. return light;
  25825. }
  25826. var camera = this.getCameraByID(id);
  25827. if (camera) {
  25828. return camera;
  25829. }
  25830. var bone = this.getBoneByID(id);
  25831. return bone;
  25832. };
  25833. /**
  25834. * Gets a node (Mesh, Camera, Light) using a given name
  25835. * @param name defines the name to search for
  25836. * @return the found node or null if not found at all.
  25837. */
  25838. Scene.prototype.getNodeByName = function (name) {
  25839. var mesh = this.getMeshByName(name);
  25840. if (mesh) {
  25841. return mesh;
  25842. }
  25843. var light = this.getLightByName(name);
  25844. if (light) {
  25845. return light;
  25846. }
  25847. var camera = this.getCameraByName(name);
  25848. if (camera) {
  25849. return camera;
  25850. }
  25851. var bone = this.getBoneByName(name);
  25852. return bone;
  25853. };
  25854. /**
  25855. * Gets a mesh using a given name
  25856. * @param name defines the name to search for
  25857. * @return the found mesh or null if not found at all.
  25858. */
  25859. Scene.prototype.getMeshByName = function (name) {
  25860. for (var index = 0; index < this.meshes.length; index++) {
  25861. if (this.meshes[index].name === name) {
  25862. return this.meshes[index];
  25863. }
  25864. }
  25865. return null;
  25866. };
  25867. /**
  25868. * Gets a transform node using a given name
  25869. * @param name defines the name to search for
  25870. * @return the found transform node or null if not found at all.
  25871. */
  25872. Scene.prototype.getTransformNodeByName = function (name) {
  25873. for (var index = 0; index < this.transformNodes.length; index++) {
  25874. if (this.transformNodes[index].name === name) {
  25875. return this.transformNodes[index];
  25876. }
  25877. }
  25878. return null;
  25879. };
  25880. /**
  25881. * Gets a sound using a given name
  25882. * @param name defines the name to search for
  25883. * @return the found sound or null if not found at all.
  25884. */
  25885. Scene.prototype.getSoundByName = function (name) {
  25886. var index;
  25887. if (BABYLON.AudioEngine) {
  25888. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  25889. if (this.mainSoundTrack.soundCollection[index].name === name) {
  25890. return this.mainSoundTrack.soundCollection[index];
  25891. }
  25892. }
  25893. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  25894. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  25895. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  25896. return this.soundTracks[sdIndex].soundCollection[index];
  25897. }
  25898. }
  25899. }
  25900. }
  25901. return null;
  25902. };
  25903. /**
  25904. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  25905. * @param id defines the id to search for
  25906. * @return the found skeleton or null if not found at all.
  25907. */
  25908. Scene.prototype.getLastSkeletonByID = function (id) {
  25909. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  25910. if (this.skeletons[index].id === id) {
  25911. return this.skeletons[index];
  25912. }
  25913. }
  25914. return null;
  25915. };
  25916. /**
  25917. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  25918. * @param id defines the id to search for
  25919. * @return the found skeleton or null if not found at all.
  25920. */
  25921. Scene.prototype.getSkeletonById = function (id) {
  25922. for (var index = 0; index < this.skeletons.length; index++) {
  25923. if (this.skeletons[index].id === id) {
  25924. return this.skeletons[index];
  25925. }
  25926. }
  25927. return null;
  25928. };
  25929. /**
  25930. * Gets a skeleton using a given name
  25931. * @param name defines the name to search for
  25932. * @return the found skeleton or null if not found at all.
  25933. */
  25934. Scene.prototype.getSkeletonByName = function (name) {
  25935. for (var index = 0; index < this.skeletons.length; index++) {
  25936. if (this.skeletons[index].name === name) {
  25937. return this.skeletons[index];
  25938. }
  25939. }
  25940. return null;
  25941. };
  25942. /**
  25943. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  25944. * @param id defines the id to search for
  25945. * @return the found morph target manager or null if not found at all.
  25946. */
  25947. Scene.prototype.getMorphTargetManagerById = function (id) {
  25948. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  25949. if (this.morphTargetManagers[index].uniqueId === id) {
  25950. return this.morphTargetManagers[index];
  25951. }
  25952. }
  25953. return null;
  25954. };
  25955. /**
  25956. * Gets a boolean indicating if the given mesh is active
  25957. * @param mesh defines the mesh to look for
  25958. * @returns true if the mesh is in the active list
  25959. */
  25960. Scene.prototype.isActiveMesh = function (mesh) {
  25961. return (this._activeMeshes.indexOf(mesh) !== -1);
  25962. };
  25963. /**
  25964. * Return a the first highlight layer of the scene with a given name.
  25965. * @param name The name of the highlight layer to look for.
  25966. * @return The highlight layer if found otherwise null.
  25967. */
  25968. Scene.prototype.getHighlightLayerByName = function (name) {
  25969. for (var index = 0; index < this.effectLayers.length; index++) {
  25970. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  25971. return this.effectLayers[index];
  25972. }
  25973. }
  25974. return null;
  25975. };
  25976. /**
  25977. * Return a the first highlight layer of the scene with a given name.
  25978. * @param name The name of the highlight layer to look for.
  25979. * @return The highlight layer if found otherwise null.
  25980. */
  25981. Scene.prototype.getGlowLayerByName = function (name) {
  25982. for (var index = 0; index < this.effectLayers.length; index++) {
  25983. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  25984. return this.effectLayers[index];
  25985. }
  25986. }
  25987. return null;
  25988. };
  25989. Object.defineProperty(Scene.prototype, "uid", {
  25990. /**
  25991. * Return a unique id as a string which can serve as an identifier for the scene
  25992. */
  25993. get: function () {
  25994. if (!this._uid) {
  25995. this._uid = BABYLON.Tools.RandomId();
  25996. }
  25997. return this._uid;
  25998. },
  25999. enumerable: true,
  26000. configurable: true
  26001. });
  26002. /**
  26003. * Add an externaly attached data from its key.
  26004. * This method call will fail and return false, if such key already exists.
  26005. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  26006. * @param key the unique key that identifies the data
  26007. * @param data the data object to associate to the key for this Engine instance
  26008. * @return true if no such key were already present and the data was added successfully, false otherwise
  26009. */
  26010. Scene.prototype.addExternalData = function (key, data) {
  26011. if (!this._externalData) {
  26012. this._externalData = new BABYLON.StringDictionary();
  26013. }
  26014. return this._externalData.add(key, data);
  26015. };
  26016. /**
  26017. * Get an externaly attached data from its key
  26018. * @param key the unique key that identifies the data
  26019. * @return the associated data, if present (can be null), or undefined if not present
  26020. */
  26021. Scene.prototype.getExternalData = function (key) {
  26022. if (!this._externalData) {
  26023. return null;
  26024. }
  26025. return this._externalData.get(key);
  26026. };
  26027. /**
  26028. * Get an externaly attached data from its key, create it using a factory if it's not already present
  26029. * @param key the unique key that identifies the data
  26030. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  26031. * @return the associated data, can be null if the factory returned null.
  26032. */
  26033. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  26034. if (!this._externalData) {
  26035. this._externalData = new BABYLON.StringDictionary();
  26036. }
  26037. return this._externalData.getOrAddWithFactory(key, factory);
  26038. };
  26039. /**
  26040. * Remove an externaly attached data from the Engine instance
  26041. * @param key the unique key that identifies the data
  26042. * @return true if the data was successfully removed, false if it doesn't exist
  26043. */
  26044. Scene.prototype.removeExternalData = function (key) {
  26045. return this._externalData.remove(key);
  26046. };
  26047. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  26048. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  26049. if (mesh.showSubMeshesBoundingBox) {
  26050. var boundingInfo = subMesh.getBoundingInfo();
  26051. if (boundingInfo !== null && boundingInfo !== undefined) {
  26052. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  26053. }
  26054. }
  26055. var material = subMesh.getMaterial();
  26056. if (material !== null && material !== undefined) {
  26057. // Render targets
  26058. if (material.getRenderTargetTextures !== undefined) {
  26059. if (this._processedMaterials.indexOf(material) === -1) {
  26060. this._processedMaterials.push(material);
  26061. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  26062. }
  26063. }
  26064. // Dispatch
  26065. this._activeIndices.addCount(subMesh.indexCount, false);
  26066. this._renderingManager.dispatch(subMesh, mesh, material);
  26067. }
  26068. }
  26069. };
  26070. /**
  26071. * Clear the processed materials smart array preventing retention point in material dispose.
  26072. */
  26073. Scene.prototype.freeProcessedMaterials = function () {
  26074. this._processedMaterials.dispose();
  26075. };
  26076. /**
  26077. * Clear the active meshes smart array preventing retention point in mesh dispose.
  26078. */
  26079. Scene.prototype.freeActiveMeshes = function () {
  26080. this._activeMeshes.dispose();
  26081. if (this.activeCamera && this.activeCamera._activeMeshes) {
  26082. this.activeCamera._activeMeshes.dispose();
  26083. }
  26084. if (this.activeCameras) {
  26085. for (var i = 0; i < this.activeCameras.length; i++) {
  26086. var activeCamera = this.activeCameras[i];
  26087. if (activeCamera && activeCamera._activeMeshes) {
  26088. activeCamera._activeMeshes.dispose();
  26089. }
  26090. }
  26091. }
  26092. };
  26093. /**
  26094. * Clear the info related to rendering groups preventing retention points during dispose.
  26095. */
  26096. Scene.prototype.freeRenderingGroups = function () {
  26097. if (this._renderingManager) {
  26098. this._renderingManager.freeRenderingGroups();
  26099. }
  26100. if (this.textures) {
  26101. for (var i = 0; i < this.textures.length; i++) {
  26102. var texture = this.textures[i];
  26103. if (texture && texture.renderList) {
  26104. texture.freeRenderingGroups();
  26105. }
  26106. }
  26107. }
  26108. };
  26109. /** @ignore */
  26110. Scene.prototype._isInIntermediateRendering = function () {
  26111. return this._intermediateRendering;
  26112. };
  26113. /**
  26114. * Defines the current active mesh candidate provider
  26115. * @param provider defines the provider to use
  26116. */
  26117. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  26118. this._activeMeshCandidateProvider = provider;
  26119. };
  26120. /**
  26121. * Gets the current active mesh candidate provider
  26122. * @returns the current active mesh candidate provider
  26123. */
  26124. Scene.prototype.getActiveMeshCandidateProvider = function () {
  26125. return this._activeMeshCandidateProvider;
  26126. };
  26127. /**
  26128. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  26129. * @returns the current scene
  26130. */
  26131. Scene.prototype.freezeActiveMeshes = function () {
  26132. if (!this.activeCamera) {
  26133. return this;
  26134. }
  26135. if (!this._frustumPlanes) {
  26136. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  26137. }
  26138. this._evaluateActiveMeshes();
  26139. this._activeMeshesFrozen = true;
  26140. return this;
  26141. };
  26142. /**
  26143. * Use this function to restart evaluating active meshes on every frame
  26144. * @returns the current scene
  26145. */
  26146. Scene.prototype.unfreezeActiveMeshes = function () {
  26147. this._activeMeshesFrozen = false;
  26148. return this;
  26149. };
  26150. Scene.prototype._evaluateActiveMeshes = function () {
  26151. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  26152. return;
  26153. }
  26154. if (!this.activeCamera) {
  26155. return;
  26156. }
  26157. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  26158. this.activeCamera._activeMeshes.reset();
  26159. this._activeMeshes.reset();
  26160. this._renderingManager.reset();
  26161. this._processedMaterials.reset();
  26162. this._activeParticleSystems.reset();
  26163. this._activeSkeletons.reset();
  26164. this._softwareSkinnedMeshes.reset();
  26165. if (this._boundingBoxRenderer) {
  26166. this._boundingBoxRenderer.reset();
  26167. }
  26168. // Meshes
  26169. var meshes;
  26170. var len;
  26171. var checkIsEnabled = true;
  26172. // Determine mesh candidates
  26173. if (this._activeMeshCandidateProvider !== undefined) {
  26174. // Use _activeMeshCandidateProvider
  26175. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  26176. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  26177. if (meshes !== undefined) {
  26178. len = meshes.length;
  26179. }
  26180. else {
  26181. len = 0;
  26182. }
  26183. }
  26184. else if (this._selectionOctree !== undefined) {
  26185. // Octree
  26186. var selection = this._selectionOctree.select(this._frustumPlanes);
  26187. meshes = selection.data;
  26188. len = selection.length;
  26189. }
  26190. else {
  26191. // Full scene traversal
  26192. len = this.meshes.length;
  26193. meshes = this.meshes;
  26194. }
  26195. // Check each mesh
  26196. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  26197. mesh = meshes[meshIndex];
  26198. if (mesh.isBlocked) {
  26199. continue;
  26200. }
  26201. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  26202. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  26203. continue;
  26204. }
  26205. mesh.computeWorldMatrix();
  26206. // Intersections
  26207. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  26208. this._meshesForIntersections.pushNoDuplicate(mesh);
  26209. }
  26210. // Switch to current LOD
  26211. meshLOD = mesh.getLOD(this.activeCamera);
  26212. if (meshLOD === undefined || meshLOD === null) {
  26213. continue;
  26214. }
  26215. mesh._preActivate();
  26216. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  26217. this._activeMeshes.push(mesh);
  26218. this.activeCamera._activeMeshes.push(mesh);
  26219. mesh._activate(this._renderId);
  26220. if (meshLOD !== mesh) {
  26221. meshLOD._activate(this._renderId);
  26222. }
  26223. this._activeMesh(mesh, meshLOD);
  26224. }
  26225. }
  26226. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  26227. // Particle systems
  26228. if (this.particlesEnabled) {
  26229. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  26230. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  26231. var particleSystem = this.particleSystems[particleIndex];
  26232. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  26233. continue;
  26234. }
  26235. var emitter = particleSystem.emitter;
  26236. if (!emitter.position || emitter.isEnabled()) {
  26237. this._activeParticleSystems.push(particleSystem);
  26238. particleSystem.animate();
  26239. this._renderingManager.dispatchParticles(particleSystem);
  26240. }
  26241. }
  26242. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  26243. }
  26244. };
  26245. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  26246. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  26247. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  26248. mesh.skeleton.prepare();
  26249. }
  26250. if (!mesh.computeBonesUsingShaders) {
  26251. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  26252. }
  26253. }
  26254. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  26255. var boundingInfo = sourceMesh.getBoundingInfo();
  26256. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  26257. }
  26258. if (mesh !== undefined && mesh !== null
  26259. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  26260. // Submeshes Octrees
  26261. var len;
  26262. var subMeshes;
  26263. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  26264. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  26265. len = intersections.length;
  26266. subMeshes = intersections.data;
  26267. }
  26268. else {
  26269. subMeshes = mesh.subMeshes;
  26270. len = subMeshes.length;
  26271. }
  26272. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  26273. subMesh = subMeshes[subIndex];
  26274. this._evaluateSubMesh(subMesh, mesh);
  26275. }
  26276. }
  26277. };
  26278. /**
  26279. * Update the transform matrix to update from the current active camera
  26280. * @param force defines a boolean used to force the update even if cache is up to date
  26281. */
  26282. Scene.prototype.updateTransformMatrix = function (force) {
  26283. if (!this.activeCamera) {
  26284. return;
  26285. }
  26286. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  26287. };
  26288. /**
  26289. * Defines an alternate camera (used mostly in VR-like scenario where two cameras can render the same scene from a slightly different point of view)
  26290. * @param alternateCamera defines the camera to use
  26291. */
  26292. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  26293. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  26294. };
  26295. Scene.prototype._renderForCamera = function (camera, rigParent) {
  26296. if (camera && camera._skipRendering) {
  26297. return;
  26298. }
  26299. var engine = this._engine;
  26300. this.activeCamera = camera;
  26301. if (!this.activeCamera)
  26302. throw new Error("Active camera not set");
  26303. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  26304. // Viewport
  26305. engine.setViewport(this.activeCamera.viewport);
  26306. // Camera
  26307. this.resetCachedMaterial();
  26308. this._renderId++;
  26309. this.updateTransformMatrix();
  26310. if (camera._alternateCamera) {
  26311. this.updateAlternateTransformMatrix(camera._alternateCamera);
  26312. this._alternateRendering = true;
  26313. }
  26314. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  26315. // Meshes
  26316. this._evaluateActiveMeshes();
  26317. // Software skinning
  26318. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  26319. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  26320. mesh.applySkeleton(mesh.skeleton);
  26321. }
  26322. // Render targets
  26323. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  26324. var needsRestoreFrameBuffer = false;
  26325. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  26326. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  26327. }
  26328. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  26329. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  26330. }
  26331. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  26332. this._intermediateRendering = true;
  26333. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  26334. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  26335. var renderTarget = this._renderTargets.data[renderIndex];
  26336. if (renderTarget._shouldRender()) {
  26337. this._renderId++;
  26338. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  26339. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  26340. }
  26341. }
  26342. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  26343. this._intermediateRendering = false;
  26344. this._renderId++;
  26345. needsRestoreFrameBuffer = true; // Restore back buffer
  26346. }
  26347. // Render EffecttLayer Texture
  26348. var stencilState = this._engine.getStencilBuffer();
  26349. var renderEffects = false;
  26350. var needStencil = false;
  26351. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  26352. this._intermediateRendering = true;
  26353. for (var i = 0; i < this.effectLayers.length; i++) {
  26354. var effectLayer = this.effectLayers[i];
  26355. if (effectLayer.shouldRender() &&
  26356. (!effectLayer.camera ||
  26357. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  26358. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  26359. renderEffects = true;
  26360. needStencil = needStencil || effectLayer.needStencil();
  26361. var renderTarget = effectLayer._mainTexture;
  26362. if (renderTarget._shouldRender()) {
  26363. this._renderId++;
  26364. renderTarget.render(false, false);
  26365. needsRestoreFrameBuffer = true;
  26366. }
  26367. }
  26368. }
  26369. this._intermediateRendering = false;
  26370. this._renderId++;
  26371. }
  26372. if (needsRestoreFrameBuffer) {
  26373. engine.restoreDefaultFramebuffer(); // Restore back buffer
  26374. }
  26375. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  26376. // Prepare Frame
  26377. this.postProcessManager._prepareFrame();
  26378. // Backgrounds
  26379. var layerIndex;
  26380. var layer;
  26381. if (this.layers.length) {
  26382. engine.setDepthBuffer(false);
  26383. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  26384. layer = this.layers[layerIndex];
  26385. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  26386. layer.render();
  26387. }
  26388. }
  26389. engine.setDepthBuffer(true);
  26390. }
  26391. // Activate effect Layer stencil
  26392. if (needStencil) {
  26393. this._engine.setStencilBuffer(true);
  26394. }
  26395. // Render
  26396. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  26397. this._renderingManager.render(null, null, true, true);
  26398. this.onAfterDrawPhaseObservable.notifyObservers(this);
  26399. // Restore effect Layer stencil
  26400. if (needStencil) {
  26401. this._engine.setStencilBuffer(stencilState);
  26402. }
  26403. // Bounding boxes
  26404. if (this._boundingBoxRenderer) {
  26405. this._boundingBoxRenderer.render();
  26406. }
  26407. // Lens flares
  26408. if (this.lensFlaresEnabled) {
  26409. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  26410. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  26411. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  26412. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  26413. lensFlareSystem.render();
  26414. }
  26415. }
  26416. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  26417. }
  26418. // Effect Layer
  26419. if (renderEffects) {
  26420. engine.setDepthBuffer(false);
  26421. for (var i = 0; i < this.effectLayers.length; i++) {
  26422. if (this.effectLayers[i].shouldRender()) {
  26423. this.effectLayers[i].render();
  26424. }
  26425. }
  26426. engine.setDepthBuffer(true);
  26427. }
  26428. // Foregrounds
  26429. if (this.layers.length) {
  26430. engine.setDepthBuffer(false);
  26431. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  26432. layer = this.layers[layerIndex];
  26433. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  26434. layer.render();
  26435. }
  26436. }
  26437. engine.setDepthBuffer(true);
  26438. }
  26439. // Finalize frame
  26440. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  26441. // Reset some special arrays
  26442. this._renderTargets.reset();
  26443. this._alternateRendering = false;
  26444. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  26445. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  26446. };
  26447. Scene.prototype._processSubCameras = function (camera) {
  26448. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  26449. this._renderForCamera(camera);
  26450. return;
  26451. }
  26452. // rig cameras
  26453. for (var index = 0; index < camera._rigCameras.length; index++) {
  26454. this._renderForCamera(camera._rigCameras[index], camera);
  26455. }
  26456. this.activeCamera = camera;
  26457. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  26458. };
  26459. Scene.prototype._checkIntersections = function () {
  26460. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  26461. var sourceMesh = this._meshesForIntersections.data[index];
  26462. if (!sourceMesh.actionManager) {
  26463. continue;
  26464. }
  26465. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  26466. var action = sourceMesh.actionManager.actions[actionIndex];
  26467. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  26468. var parameters = action.getTriggerParameter();
  26469. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  26470. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  26471. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  26472. if (areIntersecting && currentIntersectionInProgress === -1) {
  26473. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  26474. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  26475. sourceMesh._intersectionsInProgress.push(otherMesh);
  26476. }
  26477. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  26478. sourceMesh._intersectionsInProgress.push(otherMesh);
  26479. }
  26480. }
  26481. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  26482. //They intersected, and now they don't.
  26483. //is this trigger an exit trigger? execute an event.
  26484. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  26485. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  26486. }
  26487. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  26488. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  26489. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  26490. }
  26491. }
  26492. }
  26493. }
  26494. }
  26495. };
  26496. /**
  26497. * Render the scene
  26498. */
  26499. Scene.prototype.render = function () {
  26500. if (this.isDisposed) {
  26501. return;
  26502. }
  26503. this._activeParticles.fetchNewFrame();
  26504. this._totalVertices.fetchNewFrame();
  26505. this._activeIndices.fetchNewFrame();
  26506. this._activeBones.fetchNewFrame();
  26507. this._meshesForIntersections.reset();
  26508. this.resetCachedMaterial();
  26509. this.onBeforeAnimationsObservable.notifyObservers(this);
  26510. // Actions
  26511. if (this.actionManager) {
  26512. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  26513. }
  26514. //Simplification Queue
  26515. if (this.simplificationQueue && !this.simplificationQueue.running) {
  26516. this.simplificationQueue.executeNext();
  26517. }
  26518. if (this._engine.isDeterministicLockStep()) {
  26519. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  26520. var defaultFPS = (60.0 / 1000.0);
  26521. var defaultFrameTime = 1000 / 60; // frame time in MS
  26522. if (this._physicsEngine) {
  26523. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  26524. }
  26525. var stepsTaken = 0;
  26526. var maxSubSteps = this._engine.getLockstepMaxSteps();
  26527. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  26528. internalSteps = Math.min(internalSteps, maxSubSteps);
  26529. do {
  26530. this.onBeforeStepObservable.notifyObservers(this);
  26531. // Animations
  26532. this._animationRatio = defaultFrameTime * defaultFPS;
  26533. this._animate();
  26534. this.onAfterAnimationsObservable.notifyObservers(this);
  26535. // Physics
  26536. if (this._physicsEngine) {
  26537. this.onBeforePhysicsObservable.notifyObservers(this);
  26538. this._physicsEngine._step(defaultFrameTime / 1000);
  26539. this.onAfterPhysicsObservable.notifyObservers(this);
  26540. }
  26541. this.onAfterStepObservable.notifyObservers(this);
  26542. this._currentStepId++;
  26543. stepsTaken++;
  26544. deltaTime -= defaultFrameTime;
  26545. } while (deltaTime > 0 && stepsTaken < internalSteps);
  26546. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  26547. }
  26548. else {
  26549. // Animations
  26550. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  26551. this._animationRatio = deltaTime * (60.0 / 1000.0);
  26552. this._animate();
  26553. this.onAfterAnimationsObservable.notifyObservers(this);
  26554. // Physics
  26555. if (this._physicsEngine) {
  26556. this.onBeforePhysicsObservable.notifyObservers(this);
  26557. this._physicsEngine._step(deltaTime / 1000.0);
  26558. this.onAfterPhysicsObservable.notifyObservers(this);
  26559. }
  26560. }
  26561. // update gamepad manager
  26562. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  26563. this._gamepadManager._checkGamepadsStatus();
  26564. }
  26565. // Update Cameras
  26566. if (this.activeCameras.length > 0) {
  26567. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  26568. var camera = this.activeCameras[cameraIndex];
  26569. camera.update();
  26570. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  26571. // rig cameras
  26572. for (var index = 0; index < camera._rigCameras.length; index++) {
  26573. camera._rigCameras[index].update();
  26574. }
  26575. }
  26576. }
  26577. }
  26578. else if (this.activeCamera) {
  26579. this.activeCamera.update();
  26580. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  26581. // rig cameras
  26582. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  26583. this.activeCamera._rigCameras[index].update();
  26584. }
  26585. }
  26586. }
  26587. // Before render
  26588. this.onBeforeRenderObservable.notifyObservers(this);
  26589. // Customs render targets
  26590. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  26591. var engine = this.getEngine();
  26592. var currentActiveCamera = this.activeCamera;
  26593. if (this.renderTargetsEnabled) {
  26594. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  26595. this._intermediateRendering = true;
  26596. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  26597. var renderTarget = this.customRenderTargets[customIndex];
  26598. if (renderTarget._shouldRender()) {
  26599. this._renderId++;
  26600. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  26601. if (!this.activeCamera)
  26602. throw new Error("Active camera not set");
  26603. // Viewport
  26604. engine.setViewport(this.activeCamera.viewport);
  26605. // Camera
  26606. this.updateTransformMatrix();
  26607. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  26608. }
  26609. }
  26610. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  26611. this._intermediateRendering = false;
  26612. this._renderId++;
  26613. }
  26614. // Restore back buffer
  26615. if (this.customRenderTargets.length > 0) {
  26616. engine.restoreDefaultFramebuffer();
  26617. }
  26618. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  26619. this.activeCamera = currentActiveCamera;
  26620. // Procedural textures
  26621. if (this.proceduralTexturesEnabled) {
  26622. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  26623. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  26624. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  26625. if (proceduralTexture._shouldRender()) {
  26626. proceduralTexture.render();
  26627. }
  26628. }
  26629. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  26630. }
  26631. // Clear
  26632. if (this.autoClearDepthAndStencil || this.autoClear) {
  26633. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  26634. }
  26635. // Shadows
  26636. if (this.shadowsEnabled) {
  26637. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  26638. var light = this.lights[lightIndex];
  26639. var shadowGenerator = light.getShadowGenerator();
  26640. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  26641. var shadowMap = (shadowGenerator.getShadowMap());
  26642. if (this.textures.indexOf(shadowMap) !== -1) {
  26643. this._renderTargets.push(shadowMap);
  26644. }
  26645. }
  26646. }
  26647. }
  26648. // Depth renderer
  26649. for (var key in this._depthRenderer) {
  26650. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  26651. }
  26652. // Geometry renderer
  26653. if (this._geometryBufferRenderer) {
  26654. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  26655. }
  26656. // RenderPipeline
  26657. if (this._postProcessRenderPipelineManager) {
  26658. this._postProcessRenderPipelineManager.update();
  26659. }
  26660. // Multi-cameras?
  26661. if (this.activeCameras.length > 0) {
  26662. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  26663. if (cameraIndex > 0) {
  26664. this._engine.clear(null, false, true, true);
  26665. }
  26666. this._processSubCameras(this.activeCameras[cameraIndex]);
  26667. }
  26668. }
  26669. else {
  26670. if (!this.activeCamera) {
  26671. throw new Error("No camera defined");
  26672. }
  26673. this._processSubCameras(this.activeCamera);
  26674. }
  26675. // Intersection checks
  26676. this._checkIntersections();
  26677. // Update the audio listener attached to the camera
  26678. if (BABYLON.AudioEngine) {
  26679. this._updateAudioParameters();
  26680. }
  26681. // After render
  26682. if (this.afterRender) {
  26683. this.afterRender();
  26684. }
  26685. this.onAfterRenderObservable.notifyObservers(this);
  26686. // Cleaning
  26687. for (var index = 0; index < this._toBeDisposed.length; index++) {
  26688. var data = this._toBeDisposed.data[index];
  26689. if (data) {
  26690. data.dispose();
  26691. }
  26692. this._toBeDisposed[index] = null;
  26693. }
  26694. this._toBeDisposed.reset();
  26695. if (this.dumpNextRenderTargets) {
  26696. this.dumpNextRenderTargets = false;
  26697. }
  26698. this._activeBones.addCount(0, true);
  26699. this._activeIndices.addCount(0, true);
  26700. this._activeParticles.addCount(0, true);
  26701. };
  26702. Scene.prototype._updateAudioParameters = function () {
  26703. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  26704. return;
  26705. }
  26706. var listeningCamera;
  26707. var audioEngine = BABYLON.Engine.audioEngine;
  26708. if (this.activeCameras.length > 0) {
  26709. listeningCamera = this.activeCameras[0];
  26710. }
  26711. else {
  26712. listeningCamera = this.activeCamera;
  26713. }
  26714. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  26715. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  26716. // for VR cameras
  26717. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  26718. listeningCamera = listeningCamera.rigCameras[0];
  26719. }
  26720. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  26721. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  26722. cameraDirection.normalize();
  26723. // To avoid some errors on GearVR
  26724. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  26725. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  26726. }
  26727. var i;
  26728. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  26729. var sound = this.mainSoundTrack.soundCollection[i];
  26730. if (sound.useCustomAttenuation) {
  26731. sound.updateDistanceFromListener();
  26732. }
  26733. }
  26734. for (i = 0; i < this.soundTracks.length; i++) {
  26735. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  26736. sound = this.soundTracks[i].soundCollection[j];
  26737. if (sound.useCustomAttenuation) {
  26738. sound.updateDistanceFromListener();
  26739. }
  26740. }
  26741. }
  26742. }
  26743. };
  26744. Object.defineProperty(Scene.prototype, "audioEnabled", {
  26745. // Audio
  26746. /**
  26747. * Gets or sets if audio support is enabled
  26748. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  26749. */
  26750. get: function () {
  26751. return this._audioEnabled;
  26752. },
  26753. set: function (value) {
  26754. this._audioEnabled = value;
  26755. if (BABYLON.AudioEngine) {
  26756. if (this._audioEnabled) {
  26757. this._enableAudio();
  26758. }
  26759. else {
  26760. this._disableAudio();
  26761. }
  26762. }
  26763. },
  26764. enumerable: true,
  26765. configurable: true
  26766. });
  26767. Scene.prototype._disableAudio = function () {
  26768. var i;
  26769. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  26770. this.mainSoundTrack.soundCollection[i].pause();
  26771. }
  26772. for (i = 0; i < this.soundTracks.length; i++) {
  26773. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  26774. this.soundTracks[i].soundCollection[j].pause();
  26775. }
  26776. }
  26777. };
  26778. Scene.prototype._enableAudio = function () {
  26779. var i;
  26780. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  26781. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  26782. this.mainSoundTrack.soundCollection[i].play();
  26783. }
  26784. }
  26785. for (i = 0; i < this.soundTracks.length; i++) {
  26786. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  26787. if (this.soundTracks[i].soundCollection[j].isPaused) {
  26788. this.soundTracks[i].soundCollection[j].play();
  26789. }
  26790. }
  26791. }
  26792. };
  26793. Object.defineProperty(Scene.prototype, "headphone", {
  26794. /**
  26795. * Gets or sets if audio will be output to headphones
  26796. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  26797. */
  26798. get: function () {
  26799. return this._headphone;
  26800. },
  26801. set: function (value) {
  26802. this._headphone = value;
  26803. if (BABYLON.AudioEngine) {
  26804. if (this._headphone) {
  26805. this._switchAudioModeForHeadphones();
  26806. }
  26807. else {
  26808. this._switchAudioModeForNormalSpeakers();
  26809. }
  26810. }
  26811. },
  26812. enumerable: true,
  26813. configurable: true
  26814. });
  26815. Scene.prototype._switchAudioModeForHeadphones = function () {
  26816. this.mainSoundTrack.switchPanningModelToHRTF();
  26817. for (var i = 0; i < this.soundTracks.length; i++) {
  26818. this.soundTracks[i].switchPanningModelToHRTF();
  26819. }
  26820. };
  26821. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  26822. this.mainSoundTrack.switchPanningModelToEqualPower();
  26823. for (var i = 0; i < this.soundTracks.length; i++) {
  26824. this.soundTracks[i].switchPanningModelToEqualPower();
  26825. }
  26826. };
  26827. /**
  26828. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  26829. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  26830. * @returns the created depth renderer
  26831. */
  26832. Scene.prototype.enableDepthRenderer = function (camera) {
  26833. camera = camera || this.activeCamera;
  26834. if (!camera) {
  26835. throw "No camera available to enable depth renderer";
  26836. }
  26837. if (!this._depthRenderer[camera.id]) {
  26838. var textureType = 0;
  26839. if (this._engine.getCaps().textureHalfFloatRender) {
  26840. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  26841. }
  26842. else if (this._engine.getCaps().textureFloatRender) {
  26843. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  26844. }
  26845. else {
  26846. throw "Depth renderer does not support int texture type";
  26847. }
  26848. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  26849. }
  26850. return this._depthRenderer[camera.id];
  26851. };
  26852. /**
  26853. * Disables a depth renderer for a given camera
  26854. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  26855. */
  26856. Scene.prototype.disableDepthRenderer = function (camera) {
  26857. camera = camera || this.activeCamera;
  26858. if (!camera || !this._depthRenderer[camera.id]) {
  26859. return;
  26860. }
  26861. this._depthRenderer[camera.id].dispose();
  26862. delete this._depthRenderer[camera.id];
  26863. };
  26864. /**
  26865. * Enables a GeometryBufferRender and associates it with the scene
  26866. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  26867. * @returns the GeometryBufferRenderer
  26868. */
  26869. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  26870. if (ratio === void 0) { ratio = 1; }
  26871. if (this._geometryBufferRenderer) {
  26872. return this._geometryBufferRenderer;
  26873. }
  26874. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  26875. if (!this._geometryBufferRenderer.isSupported) {
  26876. this._geometryBufferRenderer = null;
  26877. }
  26878. return this._geometryBufferRenderer;
  26879. };
  26880. /**
  26881. * Disables the GeometryBufferRender associated with the scene
  26882. */
  26883. Scene.prototype.disableGeometryBufferRenderer = function () {
  26884. if (!this._geometryBufferRenderer) {
  26885. return;
  26886. }
  26887. this._geometryBufferRenderer.dispose();
  26888. this._geometryBufferRenderer = null;
  26889. };
  26890. /**
  26891. * Freeze all materials
  26892. * A frozen material will not be updatable but should be faster to render
  26893. */
  26894. Scene.prototype.freezeMaterials = function () {
  26895. for (var i = 0; i < this.materials.length; i++) {
  26896. this.materials[i].freeze();
  26897. }
  26898. };
  26899. /**
  26900. * Unfreeze all materials
  26901. * A frozen material will not be updatable but should be faster to render
  26902. */
  26903. Scene.prototype.unfreezeMaterials = function () {
  26904. for (var i = 0; i < this.materials.length; i++) {
  26905. this.materials[i].unfreeze();
  26906. }
  26907. };
  26908. /**
  26909. * Releases all held ressources
  26910. */
  26911. Scene.prototype.dispose = function () {
  26912. this.beforeRender = null;
  26913. this.afterRender = null;
  26914. this.skeletons = [];
  26915. this.morphTargetManagers = [];
  26916. this.importedMeshesFiles = new Array();
  26917. this.stopAllAnimations();
  26918. this.resetCachedMaterial();
  26919. for (var key in this._depthRenderer) {
  26920. this._depthRenderer[key].dispose();
  26921. }
  26922. if (this._gamepadManager) {
  26923. this._gamepadManager.dispose();
  26924. this._gamepadManager = null;
  26925. }
  26926. // Smart arrays
  26927. if (this.activeCamera) {
  26928. this.activeCamera._activeMeshes.dispose();
  26929. this.activeCamera = null;
  26930. }
  26931. this._activeMeshes.dispose();
  26932. this._renderingManager.dispose();
  26933. this._processedMaterials.dispose();
  26934. this._activeParticleSystems.dispose();
  26935. this._activeSkeletons.dispose();
  26936. this._softwareSkinnedMeshes.dispose();
  26937. this._renderTargets.dispose();
  26938. this._registeredForLateAnimationBindings.dispose();
  26939. if (this._boundingBoxRenderer) {
  26940. this._boundingBoxRenderer.dispose();
  26941. }
  26942. this._meshesForIntersections.dispose();
  26943. this._toBeDisposed.dispose();
  26944. // Abort active requests
  26945. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  26946. var request = _a[_i];
  26947. request.abort();
  26948. }
  26949. // Debug layer
  26950. if (this._debugLayer) {
  26951. this._debugLayer.hide();
  26952. }
  26953. // Events
  26954. this.onDisposeObservable.notifyObservers(this);
  26955. this.onDisposeObservable.clear();
  26956. this.onBeforeRenderObservable.clear();
  26957. this.onAfterRenderObservable.clear();
  26958. this.onBeforeRenderTargetsRenderObservable.clear();
  26959. this.onAfterRenderTargetsRenderObservable.clear();
  26960. this.onAfterStepObservable.clear();
  26961. this.onBeforeStepObservable.clear();
  26962. this.onBeforeActiveMeshesEvaluationObservable.clear();
  26963. this.onAfterActiveMeshesEvaluationObservable.clear();
  26964. this.onBeforeParticlesRenderingObservable.clear();
  26965. this.onAfterParticlesRenderingObservable.clear();
  26966. this.onBeforeSpritesRenderingObservable.clear();
  26967. this.onAfterSpritesRenderingObservable.clear();
  26968. this.onBeforeDrawPhaseObservable.clear();
  26969. this.onAfterDrawPhaseObservable.clear();
  26970. this.onBeforePhysicsObservable.clear();
  26971. this.onAfterPhysicsObservable.clear();
  26972. this.onBeforeAnimationsObservable.clear();
  26973. this.onAfterAnimationsObservable.clear();
  26974. this.onDataLoadedObservable.clear();
  26975. this.detachControl();
  26976. // Release sounds & sounds tracks
  26977. if (BABYLON.AudioEngine) {
  26978. this.disposeSounds();
  26979. }
  26980. // VR Helper
  26981. if (this.VRHelper) {
  26982. this.VRHelper.dispose();
  26983. }
  26984. // Detach cameras
  26985. var canvas = this._engine.getRenderingCanvas();
  26986. if (canvas) {
  26987. var index;
  26988. for (index = 0; index < this.cameras.length; index++) {
  26989. this.cameras[index].detachControl(canvas);
  26990. }
  26991. }
  26992. // Release animation groups
  26993. while (this.animationGroups.length) {
  26994. this.animationGroups[0].dispose();
  26995. }
  26996. // Release lights
  26997. while (this.lights.length) {
  26998. this.lights[0].dispose();
  26999. }
  27000. // Release meshes
  27001. while (this.meshes.length) {
  27002. this.meshes[0].dispose(true);
  27003. }
  27004. while (this.transformNodes.length) {
  27005. this.removeTransformNode(this.transformNodes[0]);
  27006. }
  27007. // Release cameras
  27008. while (this.cameras.length) {
  27009. this.cameras[0].dispose();
  27010. }
  27011. // Release materials
  27012. if (this.defaultMaterial) {
  27013. this.defaultMaterial.dispose();
  27014. }
  27015. while (this.multiMaterials.length) {
  27016. this.multiMaterials[0].dispose();
  27017. }
  27018. while (this.materials.length) {
  27019. this.materials[0].dispose();
  27020. }
  27021. // Release particles
  27022. while (this.particleSystems.length) {
  27023. this.particleSystems[0].dispose();
  27024. }
  27025. // Release sprites
  27026. while (this.spriteManagers.length) {
  27027. this.spriteManagers[0].dispose();
  27028. }
  27029. // Release postProcesses
  27030. while (this.postProcesses.length) {
  27031. this.postProcesses[0].dispose();
  27032. }
  27033. // Release layers
  27034. while (this.layers.length) {
  27035. this.layers[0].dispose();
  27036. }
  27037. while (this.effectLayers.length) {
  27038. this.effectLayers[0].dispose();
  27039. }
  27040. // Release textures
  27041. while (this.textures.length) {
  27042. this.textures[0].dispose();
  27043. }
  27044. // Release UBO
  27045. this._sceneUbo.dispose();
  27046. if (this._alternateSceneUbo) {
  27047. this._alternateSceneUbo.dispose();
  27048. }
  27049. // Post-processes
  27050. this.postProcessManager.dispose();
  27051. if (this._postProcessRenderPipelineManager) {
  27052. this._postProcessRenderPipelineManager.dispose();
  27053. }
  27054. // Physics
  27055. if (this._physicsEngine) {
  27056. this.disablePhysicsEngine();
  27057. }
  27058. // Remove from engine
  27059. index = this._engine.scenes.indexOf(this);
  27060. if (index > -1) {
  27061. this._engine.scenes.splice(index, 1);
  27062. }
  27063. this._engine.wipeCaches(true);
  27064. this._isDisposed = true;
  27065. };
  27066. Object.defineProperty(Scene.prototype, "isDisposed", {
  27067. /**
  27068. * Gets if the scene is already disposed
  27069. */
  27070. get: function () {
  27071. return this._isDisposed;
  27072. },
  27073. enumerable: true,
  27074. configurable: true
  27075. });
  27076. /**
  27077. * Releases sounds & soundtracks
  27078. */
  27079. Scene.prototype.disposeSounds = function () {
  27080. if (!this._mainSoundTrack) {
  27081. return;
  27082. }
  27083. this.mainSoundTrack.dispose();
  27084. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  27085. this.soundTracks[scIndex].dispose();
  27086. }
  27087. };
  27088. // Octrees
  27089. /**
  27090. * Get the world extend vectors with an optional filter
  27091. *
  27092. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  27093. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  27094. */
  27095. Scene.prototype.getWorldExtends = function (filterPredicate) {
  27096. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  27097. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  27098. filterPredicate = filterPredicate || (function () { return true; });
  27099. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  27100. mesh.computeWorldMatrix(true);
  27101. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  27102. return;
  27103. }
  27104. var boundingInfo = mesh.getBoundingInfo();
  27105. var minBox = boundingInfo.boundingBox.minimumWorld;
  27106. var maxBox = boundingInfo.boundingBox.maximumWorld;
  27107. BABYLON.Tools.CheckExtends(minBox, min, max);
  27108. BABYLON.Tools.CheckExtends(maxBox, min, max);
  27109. });
  27110. return {
  27111. min: min,
  27112. max: max
  27113. };
  27114. };
  27115. /**
  27116. * Creates or updates the octree used to boost selection (picking)
  27117. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  27118. * @param maxCapacity defines the maximum capacity per leaf
  27119. * @param maxDepth defines the maximum depth of the octree
  27120. * @returns an octree of AbstractMesh
  27121. */
  27122. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  27123. if (maxCapacity === void 0) { maxCapacity = 64; }
  27124. if (maxDepth === void 0) { maxDepth = 2; }
  27125. if (!this._selectionOctree) {
  27126. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  27127. }
  27128. var worldExtends = this.getWorldExtends();
  27129. // Update octree
  27130. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  27131. return this._selectionOctree;
  27132. };
  27133. // Picking
  27134. /**
  27135. * Creates a ray that can be used to pick in the scene
  27136. * @param x defines the x coordinate of the origin (on-screen)
  27137. * @param y defines the y coordinate of the origin (on-screen)
  27138. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  27139. * @param camera defines the camera to use for the picking
  27140. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  27141. * @returns a Ray
  27142. */
  27143. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  27144. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  27145. var result = BABYLON.Ray.Zero();
  27146. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  27147. return result;
  27148. };
  27149. /**
  27150. * Creates a ray that can be used to pick in the scene
  27151. * @param x defines the x coordinate of the origin (on-screen)
  27152. * @param y defines the y coordinate of the origin (on-screen)
  27153. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  27154. * @param result defines the ray where to store the picking ray
  27155. * @param camera defines the camera to use for the picking
  27156. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  27157. * @returns the current scene
  27158. */
  27159. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  27160. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  27161. var engine = this._engine;
  27162. if (!camera) {
  27163. if (!this.activeCamera)
  27164. throw new Error("Active camera not set");
  27165. camera = this.activeCamera;
  27166. }
  27167. var cameraViewport = camera.viewport;
  27168. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  27169. // Moving coordinates to local viewport world
  27170. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  27171. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  27172. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  27173. return this;
  27174. };
  27175. /**
  27176. * Creates a ray that can be used to pick in the scene
  27177. * @param x defines the x coordinate of the origin (on-screen)
  27178. * @param y defines the y coordinate of the origin (on-screen)
  27179. * @param camera defines the camera to use for the picking
  27180. * @returns a Ray
  27181. */
  27182. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  27183. var result = BABYLON.Ray.Zero();
  27184. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  27185. return result;
  27186. };
  27187. /**
  27188. * Creates a ray that can be used to pick in the scene
  27189. * @param x defines the x coordinate of the origin (on-screen)
  27190. * @param y defines the y coordinate of the origin (on-screen)
  27191. * @param result defines the ray where to store the picking ray
  27192. * @param camera defines the camera to use for the picking
  27193. * @returns the current scene
  27194. */
  27195. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  27196. if (!BABYLON.PickingInfo) {
  27197. return this;
  27198. }
  27199. var engine = this._engine;
  27200. if (!camera) {
  27201. if (!this.activeCamera)
  27202. throw new Error("Active camera not set");
  27203. camera = this.activeCamera;
  27204. }
  27205. var cameraViewport = camera.viewport;
  27206. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  27207. var identity = BABYLON.Matrix.Identity();
  27208. // Moving coordinates to local viewport world
  27209. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  27210. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  27211. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  27212. return this;
  27213. };
  27214. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  27215. if (!BABYLON.PickingInfo) {
  27216. return null;
  27217. }
  27218. var pickingInfo = null;
  27219. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  27220. var mesh = this.meshes[meshIndex];
  27221. if (predicate) {
  27222. if (!predicate(mesh)) {
  27223. continue;
  27224. }
  27225. }
  27226. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  27227. continue;
  27228. }
  27229. var world = mesh.getWorldMatrix();
  27230. var ray = rayFunction(world);
  27231. var result = mesh.intersects(ray, fastCheck);
  27232. if (!result || !result.hit)
  27233. continue;
  27234. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  27235. continue;
  27236. pickingInfo = result;
  27237. if (fastCheck) {
  27238. break;
  27239. }
  27240. }
  27241. return pickingInfo || new BABYLON.PickingInfo();
  27242. };
  27243. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  27244. if (!BABYLON.PickingInfo) {
  27245. return null;
  27246. }
  27247. var pickingInfos = new Array();
  27248. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  27249. var mesh = this.meshes[meshIndex];
  27250. if (predicate) {
  27251. if (!predicate(mesh)) {
  27252. continue;
  27253. }
  27254. }
  27255. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  27256. continue;
  27257. }
  27258. var world = mesh.getWorldMatrix();
  27259. var ray = rayFunction(world);
  27260. var result = mesh.intersects(ray, false);
  27261. if (!result || !result.hit)
  27262. continue;
  27263. pickingInfos.push(result);
  27264. }
  27265. return pickingInfos;
  27266. };
  27267. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  27268. if (!BABYLON.PickingInfo) {
  27269. return null;
  27270. }
  27271. var pickingInfo = null;
  27272. if (!camera) {
  27273. if (!this.activeCamera) {
  27274. return null;
  27275. }
  27276. camera = this.activeCamera;
  27277. }
  27278. if (this.spriteManagers.length > 0) {
  27279. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  27280. var spriteManager = this.spriteManagers[spriteIndex];
  27281. if (!spriteManager.isPickable) {
  27282. continue;
  27283. }
  27284. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  27285. if (!result || !result.hit)
  27286. continue;
  27287. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  27288. continue;
  27289. pickingInfo = result;
  27290. if (fastCheck) {
  27291. break;
  27292. }
  27293. }
  27294. }
  27295. return pickingInfo || new BABYLON.PickingInfo();
  27296. };
  27297. /** Launch a ray to try to pick a mesh in the scene
  27298. * @param x position on screen
  27299. * @param y position on screen
  27300. * @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
  27301. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  27302. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  27303. * @returns a PickingInfo
  27304. */
  27305. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  27306. var _this = this;
  27307. if (!BABYLON.PickingInfo) {
  27308. return null;
  27309. }
  27310. return this._internalPick(function (world) {
  27311. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  27312. return _this._tempPickingRay;
  27313. }, predicate, fastCheck);
  27314. };
  27315. /** Launch a ray to try to pick a sprite in the scene
  27316. * @param x position on screen
  27317. * @param y position on screen
  27318. * @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
  27319. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  27320. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  27321. * @returns a PickingInfo
  27322. */
  27323. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  27324. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  27325. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  27326. };
  27327. /** Use the given ray to pick a mesh in the scene
  27328. * @param ray The ray to use to pick meshes
  27329. * @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
  27330. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  27331. * @returns a PickingInfo
  27332. */
  27333. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  27334. var _this = this;
  27335. return this._internalPick(function (world) {
  27336. if (!_this._pickWithRayInverseMatrix) {
  27337. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  27338. }
  27339. world.invertToRef(_this._pickWithRayInverseMatrix);
  27340. if (!_this._cachedRayForTransform) {
  27341. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  27342. }
  27343. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  27344. return _this._cachedRayForTransform;
  27345. }, predicate, fastCheck);
  27346. };
  27347. /**
  27348. * Launch a ray to try to pick a mesh in the scene
  27349. * @param x X position on screen
  27350. * @param y Y position on screen
  27351. * @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
  27352. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  27353. * @returns an array of PickingInfo
  27354. */
  27355. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  27356. var _this = this;
  27357. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  27358. };
  27359. /**
  27360. * Launch a ray to try to pick a mesh in the scene
  27361. * @param ray Ray to use
  27362. * @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
  27363. * @returns an array of PickingInfo
  27364. */
  27365. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  27366. var _this = this;
  27367. return this._internalMultiPick(function (world) {
  27368. if (!_this._pickWithRayInverseMatrix) {
  27369. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  27370. }
  27371. world.invertToRef(_this._pickWithRayInverseMatrix);
  27372. if (!_this._cachedRayForTransform) {
  27373. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  27374. }
  27375. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  27376. return _this._cachedRayForTransform;
  27377. }, predicate);
  27378. };
  27379. /**
  27380. * Force the value of meshUnderPointer
  27381. * @param mesh defines the mesh to use
  27382. */
  27383. Scene.prototype.setPointerOverMesh = function (mesh) {
  27384. if (this._pointerOverMesh === mesh) {
  27385. return;
  27386. }
  27387. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  27388. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  27389. }
  27390. this._pointerOverMesh = mesh;
  27391. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  27392. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  27393. }
  27394. };
  27395. /**
  27396. * Gets the mesh under the pointer
  27397. * @returns a Mesh or null if no mesh is under the pointer
  27398. */
  27399. Scene.prototype.getPointerOverMesh = function () {
  27400. return this._pointerOverMesh;
  27401. };
  27402. /**
  27403. * Force the sprite under the pointer
  27404. * @param sprite defines the sprite to use
  27405. */
  27406. Scene.prototype.setPointerOverSprite = function (sprite) {
  27407. if (this._pointerOverSprite === sprite) {
  27408. return;
  27409. }
  27410. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  27411. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  27412. }
  27413. this._pointerOverSprite = sprite;
  27414. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  27415. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  27416. }
  27417. };
  27418. /**
  27419. * Gets the sprite under the pointer
  27420. * @returns a Sprite or null if no sprite is under the pointer
  27421. */
  27422. Scene.prototype.getPointerOverSprite = function () {
  27423. return this._pointerOverSprite;
  27424. };
  27425. // Physics
  27426. /**
  27427. * Gets the current physics engine
  27428. * @returns a PhysicsEngine or null if none attached
  27429. */
  27430. Scene.prototype.getPhysicsEngine = function () {
  27431. return this._physicsEngine;
  27432. };
  27433. /**
  27434. * Enables physics to the current scene
  27435. * @param gravity defines the scene's gravity for the physics engine
  27436. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  27437. * @return a boolean indicating if the physics engine was initialized
  27438. */
  27439. Scene.prototype.enablePhysics = function (gravity, plugin) {
  27440. if (gravity === void 0) { gravity = null; }
  27441. if (this._physicsEngine) {
  27442. return true;
  27443. }
  27444. try {
  27445. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  27446. return true;
  27447. }
  27448. catch (e) {
  27449. BABYLON.Tools.Error(e.message);
  27450. return false;
  27451. }
  27452. };
  27453. /**
  27454. * Disables and disposes the physics engine associated with the scene
  27455. */
  27456. Scene.prototype.disablePhysicsEngine = function () {
  27457. if (!this._physicsEngine) {
  27458. return;
  27459. }
  27460. this._physicsEngine.dispose();
  27461. this._physicsEngine = null;
  27462. };
  27463. /**
  27464. * Gets a boolean indicating if there is an active physics engine
  27465. * @returns a boolean indicating if there is an active physics engine
  27466. */
  27467. Scene.prototype.isPhysicsEnabled = function () {
  27468. return this._physicsEngine !== undefined;
  27469. };
  27470. /**
  27471. * Deletes a physics compound impostor
  27472. * @param compound defines the compound to delete
  27473. */
  27474. Scene.prototype.deleteCompoundImpostor = function (compound) {
  27475. var mesh = compound.parts[0].mesh;
  27476. if (mesh.physicsImpostor) {
  27477. mesh.physicsImpostor.dispose();
  27478. mesh.physicsImpostor = null;
  27479. }
  27480. };
  27481. // Misc.
  27482. /** @ignore */
  27483. Scene.prototype._rebuildGeometries = function () {
  27484. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  27485. var geometry = _a[_i];
  27486. geometry._rebuild();
  27487. }
  27488. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  27489. var mesh = _c[_b];
  27490. mesh._rebuild();
  27491. }
  27492. if (this.postProcessManager) {
  27493. this.postProcessManager._rebuild();
  27494. }
  27495. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  27496. var layer = _e[_d];
  27497. layer._rebuild();
  27498. }
  27499. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  27500. var effectLayer = _g[_f];
  27501. effectLayer._rebuild();
  27502. }
  27503. if (this._boundingBoxRenderer) {
  27504. this._boundingBoxRenderer._rebuild();
  27505. }
  27506. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  27507. var system = _j[_h];
  27508. system.rebuild();
  27509. }
  27510. if (this._postProcessRenderPipelineManager) {
  27511. this._postProcessRenderPipelineManager._rebuild();
  27512. }
  27513. };
  27514. /** @ignore */
  27515. Scene.prototype._rebuildTextures = function () {
  27516. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  27517. var texture = _a[_i];
  27518. texture._rebuild();
  27519. }
  27520. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27521. };
  27522. /**
  27523. * Creates a default light for the scene.
  27524. * @param replace Whether to replace the existing lights in the scene.
  27525. */
  27526. Scene.prototype.createDefaultLight = function (replace) {
  27527. if (replace === void 0) { replace = false; }
  27528. // Dispose existing light in replace mode.
  27529. if (replace) {
  27530. if (this.lights) {
  27531. for (var i = 0; i < this.lights.length; i++) {
  27532. this.lights[i].dispose();
  27533. }
  27534. }
  27535. }
  27536. // Light
  27537. if (this.lights.length === 0) {
  27538. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  27539. }
  27540. };
  27541. /**
  27542. * Creates a default camera for the scene.
  27543. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  27544. * @param replace Whether to replace the existing active camera in the scene.
  27545. * @param attachCameraControls Whether to attach camera controls to the canvas.
  27546. */
  27547. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  27548. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  27549. if (replace === void 0) { replace = false; }
  27550. if (attachCameraControls === void 0) { attachCameraControls = false; }
  27551. // Dispose existing camera in replace mode.
  27552. if (replace) {
  27553. if (this.activeCamera) {
  27554. this.activeCamera.dispose();
  27555. this.activeCamera = null;
  27556. }
  27557. }
  27558. // Camera
  27559. if (!this.activeCamera) {
  27560. var worldExtends = this.getWorldExtends();
  27561. var worldSize = worldExtends.max.subtract(worldExtends.min);
  27562. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  27563. var camera;
  27564. var radius = worldSize.length() * 1.5;
  27565. // empty scene scenario!
  27566. if (!isFinite(radius)) {
  27567. radius = 1;
  27568. worldCenter.copyFromFloats(0, 0, 0);
  27569. }
  27570. if (createArcRotateCamera) {
  27571. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  27572. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  27573. arcRotateCamera.wheelPrecision = 100 / radius;
  27574. camera = arcRotateCamera;
  27575. }
  27576. else {
  27577. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  27578. freeCamera.setTarget(worldCenter);
  27579. camera = freeCamera;
  27580. }
  27581. camera.minZ = radius * 0.01;
  27582. camera.maxZ = radius * 1000;
  27583. camera.speed = radius * 0.2;
  27584. this.activeCamera = camera;
  27585. var canvas = this.getEngine().getRenderingCanvas();
  27586. if (attachCameraControls && canvas) {
  27587. camera.attachControl(canvas);
  27588. }
  27589. }
  27590. };
  27591. /**
  27592. * Creates a default camera and a default light
  27593. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  27594. * @param replace defines if the camera and/or light will replace the existing ones
  27595. * @param attachCameraControls defines if attachControl will be called on the new camera
  27596. */
  27597. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  27598. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  27599. if (replace === void 0) { replace = false; }
  27600. if (attachCameraControls === void 0) { attachCameraControls = false; }
  27601. this.createDefaultLight(replace);
  27602. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  27603. };
  27604. /**
  27605. * Creates a new sky box
  27606. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  27607. * @param environmentTexture defines the texture to use as environment texture
  27608. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  27609. * @param scale defines the overall scale of the skybox
  27610. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  27611. * @returns a new mesh holding the sky box
  27612. */
  27613. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  27614. if (pbr === void 0) { pbr = false; }
  27615. if (scale === void 0) { scale = 1000; }
  27616. if (blur === void 0) { blur = 0; }
  27617. if (environmentTexture) {
  27618. this.environmentTexture = environmentTexture;
  27619. }
  27620. if (!this.environmentTexture) {
  27621. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  27622. return null;
  27623. }
  27624. // Skybox
  27625. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  27626. if (pbr) {
  27627. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  27628. hdrSkyboxMaterial.backFaceCulling = false;
  27629. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  27630. if (hdrSkyboxMaterial.reflectionTexture) {
  27631. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  27632. }
  27633. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  27634. hdrSkyboxMaterial.disableLighting = true;
  27635. hdrSkyboxMaterial.twoSidedLighting = true;
  27636. hdrSkybox.infiniteDistance = true;
  27637. hdrSkybox.material = hdrSkyboxMaterial;
  27638. }
  27639. else {
  27640. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  27641. skyboxMaterial.backFaceCulling = false;
  27642. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  27643. if (skyboxMaterial.reflectionTexture) {
  27644. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  27645. }
  27646. skyboxMaterial.disableLighting = true;
  27647. hdrSkybox.infiniteDistance = true;
  27648. hdrSkybox.material = skyboxMaterial;
  27649. }
  27650. return hdrSkybox;
  27651. };
  27652. /**
  27653. * Creates a new environment
  27654. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  27655. * @param options defines the options you can use to configure the environment
  27656. * @returns the new EnvironmentHelper
  27657. */
  27658. Scene.prototype.createDefaultEnvironment = function (options) {
  27659. if (BABYLON.EnvironmentHelper) {
  27660. return new BABYLON.EnvironmentHelper(options, this);
  27661. }
  27662. return null;
  27663. };
  27664. /**
  27665. * Creates a new VREXperienceHelper
  27666. * @see http://doc.babylonjs.com/how_to/webvr_helper
  27667. * @param webVROptions defines the options used to create the new VREXperienceHelper
  27668. * @returns a new VREXperienceHelper
  27669. */
  27670. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  27671. if (webVROptions === void 0) { webVROptions = {}; }
  27672. return new BABYLON.VRExperienceHelper(this, webVROptions);
  27673. };
  27674. // Tags
  27675. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  27676. if (tagsQuery === undefined) {
  27677. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  27678. return list;
  27679. }
  27680. var listByTags = [];
  27681. forEach = forEach || (function (item) { return; });
  27682. for (var i in list) {
  27683. var item = list[i];
  27684. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  27685. listByTags.push(item);
  27686. forEach(item);
  27687. }
  27688. }
  27689. return listByTags;
  27690. };
  27691. /**
  27692. * Get a list of meshes by tags
  27693. * @param tagsQuery defines the tags query to use
  27694. * @param forEach defines a predicate used to filter results
  27695. * @returns an array of Mesh
  27696. */
  27697. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  27698. return this._getByTags(this.meshes, tagsQuery, forEach);
  27699. };
  27700. /**
  27701. * Get a list of cameras by tags
  27702. * @param tagsQuery defines the tags query to use
  27703. * @param forEach defines a predicate used to filter results
  27704. * @returns an array of Camera
  27705. */
  27706. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  27707. return this._getByTags(this.cameras, tagsQuery, forEach);
  27708. };
  27709. /**
  27710. * Get a list of lights by tags
  27711. * @param tagsQuery defines the tags query to use
  27712. * @param forEach defines a predicate used to filter results
  27713. * @returns an array of Light
  27714. */
  27715. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  27716. return this._getByTags(this.lights, tagsQuery, forEach);
  27717. };
  27718. /**
  27719. * Get a list of materials by tags
  27720. * @param tagsQuery defines the tags query to use
  27721. * @param forEach defines a predicate used to filter results
  27722. * @returns an array of Material
  27723. */
  27724. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  27725. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  27726. };
  27727. /**
  27728. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  27729. * This allowed control for front to back rendering or reversly depending of the special needs.
  27730. *
  27731. * @param renderingGroupId The rendering group id corresponding to its index
  27732. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  27733. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  27734. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  27735. */
  27736. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  27737. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  27738. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  27739. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  27740. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  27741. };
  27742. /**
  27743. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  27744. *
  27745. * @param renderingGroupId The rendering group id corresponding to its index
  27746. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  27747. * @param depth Automatically clears depth between groups if true and autoClear is true.
  27748. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  27749. */
  27750. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  27751. if (depth === void 0) { depth = true; }
  27752. if (stencil === void 0) { stencil = true; }
  27753. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  27754. };
  27755. /**
  27756. * Will flag all materials as dirty to trigger new shader compilation
  27757. * @param flag defines the flag used to specify which material part must be marked as dirty
  27758. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  27759. */
  27760. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  27761. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  27762. var material = _a[_i];
  27763. if (predicate && !predicate(material)) {
  27764. continue;
  27765. }
  27766. material.markAsDirty(flag);
  27767. }
  27768. };
  27769. /** @ignore */
  27770. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  27771. var _this = this;
  27772. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  27773. this._activeRequests.push(request);
  27774. request.onCompleteObservable.add(function (request) {
  27775. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  27776. });
  27777. return request;
  27778. };
  27779. /** @ignore */
  27780. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  27781. var _this = this;
  27782. return new Promise(function (resolve, reject) {
  27783. _this._loadFile(url, function (data) {
  27784. resolve(data);
  27785. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  27786. reject(exception);
  27787. });
  27788. });
  27789. };
  27790. // Statics
  27791. Scene._FOGMODE_NONE = 0;
  27792. Scene._FOGMODE_EXP = 1;
  27793. Scene._FOGMODE_EXP2 = 2;
  27794. Scene._FOGMODE_LINEAR = 3;
  27795. Scene._uniqueIdCounter = 0;
  27796. /**
  27797. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  27798. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  27799. */
  27800. Scene.MinDeltaTime = 1.0;
  27801. /**
  27802. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  27803. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  27804. */
  27805. Scene.MaxDeltaTime = 1000.0;
  27806. /** The distance in pixel that you have to move to prevent some events */
  27807. Scene.DragMovementThreshold = 10; // in pixels
  27808. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  27809. Scene.LongPressDelay = 500; // in milliseconds
  27810. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  27811. Scene.DoubleClickDelay = 300; // in milliseconds
  27812. /** If you need to check double click without raising a single click at first click, enable this flag */
  27813. Scene.ExclusiveDoubleClickMode = false;
  27814. return Scene;
  27815. }());
  27816. BABYLON.Scene = Scene;
  27817. })(BABYLON || (BABYLON = {}));
  27818. //# sourceMappingURL=babylon.scene.js.map
  27819. "use strict";
  27820. var BABYLON;
  27821. (function (BABYLON) {
  27822. /**
  27823. * Set of assets to keep when moving a scene into an asset container.
  27824. */
  27825. var KeepAssets = /** @class */ (function () {
  27826. function KeepAssets() {
  27827. /**
  27828. * Cameras to keep.
  27829. */
  27830. this.cameras = new Array();
  27831. /**
  27832. * Lights to keep.
  27833. */
  27834. this.lights = new Array();
  27835. /**
  27836. * Meshes to keep.
  27837. */
  27838. this.meshes = new Array();
  27839. /**
  27840. * Skeletons to keep.
  27841. */
  27842. this.skeletons = new Array();
  27843. /**
  27844. * ParticleSystems to keep.
  27845. */
  27846. this.particleSystems = new Array();
  27847. /**
  27848. * Animations to keep.
  27849. */
  27850. this.animations = new Array();
  27851. /**
  27852. * AnimationGroups to keep.
  27853. */
  27854. this.animationGroups = new Array();
  27855. /**
  27856. * MultiMaterials to keep.
  27857. */
  27858. this.multiMaterials = new Array();
  27859. /**
  27860. * Materials to keep.
  27861. */
  27862. this.materials = new Array();
  27863. /**
  27864. * MorphTargetManagers to keep.
  27865. */
  27866. this.morphTargetManagers = new Array();
  27867. /**
  27868. * Geometries to keep.
  27869. */
  27870. this.geometries = new Array();
  27871. /**
  27872. * TransformNodes to keep.
  27873. */
  27874. this.transformNodes = new Array();
  27875. /**
  27876. * LensFlareSystems to keep.
  27877. */
  27878. this.lensFlareSystems = new Array();
  27879. /**
  27880. * ShadowGenerators to keep.
  27881. */
  27882. this.shadowGenerators = new Array();
  27883. /**
  27884. * ActionManagers to keep.
  27885. */
  27886. this.actionManagers = new Array();
  27887. /**
  27888. * Sounds to keep.
  27889. */
  27890. this.sounds = new Array();
  27891. /**
  27892. * Textures to keep.
  27893. */
  27894. this.textures = new Array();
  27895. }
  27896. return KeepAssets;
  27897. }());
  27898. BABYLON.KeepAssets = KeepAssets;
  27899. /**
  27900. * Container with a set of assets that can be added or removed from a scene.
  27901. */
  27902. var AssetContainer = /** @class */ (function () {
  27903. /**
  27904. * Instantiates an AssetContainer.
  27905. * @param scene The scene the AssetContainer belongs to.
  27906. */
  27907. function AssetContainer(scene) {
  27908. // Objects
  27909. /**
  27910. * Cameras populated in the container.
  27911. */
  27912. this.cameras = new Array();
  27913. /**
  27914. * Lights populated in the container.
  27915. */
  27916. this.lights = new Array();
  27917. /**
  27918. * Meshes populated in the container.
  27919. */
  27920. this.meshes = new Array();
  27921. /**
  27922. * Skeletons populated in the container.
  27923. */
  27924. this.skeletons = new Array();
  27925. /**
  27926. * ParticleSystems populated in the container.
  27927. */
  27928. this.particleSystems = new Array();
  27929. /**
  27930. * Animations populated in the container.
  27931. */
  27932. this.animations = new Array();
  27933. /**
  27934. * AnimationGroups populated in the container.
  27935. */
  27936. this.animationGroups = new Array();
  27937. /**
  27938. * MultiMaterials populated in the container.
  27939. */
  27940. this.multiMaterials = new Array();
  27941. /**
  27942. * Materials populated in the container.
  27943. */
  27944. this.materials = new Array();
  27945. /**
  27946. * MorphTargetManagers populated in the container.
  27947. */
  27948. this.morphTargetManagers = new Array();
  27949. /**
  27950. * Geometries populated in the container.
  27951. */
  27952. this.geometries = new Array();
  27953. /**
  27954. * TransformNodes populated in the container.
  27955. */
  27956. this.transformNodes = new Array();
  27957. /**
  27958. * LensFlareSystems populated in the container.
  27959. */
  27960. this.lensFlareSystems = new Array();
  27961. /**
  27962. * ShadowGenerators populated in the container.
  27963. */
  27964. this.shadowGenerators = new Array();
  27965. /**
  27966. * ActionManagers populated in the container.
  27967. */
  27968. this.actionManagers = new Array();
  27969. /**
  27970. * Sounds populated in the container.
  27971. */
  27972. this.sounds = new Array();
  27973. /**
  27974. * Textures populated in the container.
  27975. */
  27976. this.textures = new Array();
  27977. this.scene = scene;
  27978. }
  27979. /**
  27980. * Adds all the assets from the container to the scene.
  27981. */
  27982. AssetContainer.prototype.addAllToScene = function () {
  27983. var _this = this;
  27984. this.cameras.forEach(function (o) {
  27985. _this.scene.addCamera(o);
  27986. });
  27987. this.lights.forEach(function (o) {
  27988. _this.scene.addLight(o);
  27989. });
  27990. this.meshes.forEach(function (o) {
  27991. _this.scene.addMesh(o);
  27992. });
  27993. this.skeletons.forEach(function (o) {
  27994. _this.scene.addSkeleton(o);
  27995. });
  27996. this.particleSystems.forEach(function (o) {
  27997. _this.scene.addParticleSystem(o);
  27998. });
  27999. this.animations.forEach(function (o) {
  28000. _this.scene.addAnimation(o);
  28001. });
  28002. this.animationGroups.forEach(function (o) {
  28003. _this.scene.addAnimationGroup(o);
  28004. });
  28005. this.multiMaterials.forEach(function (o) {
  28006. _this.scene.addMultiMaterial(o);
  28007. });
  28008. this.materials.forEach(function (o) {
  28009. _this.scene.addMaterial(o);
  28010. });
  28011. this.morphTargetManagers.forEach(function (o) {
  28012. _this.scene.addMorphTargetManager(o);
  28013. });
  28014. this.geometries.forEach(function (o) {
  28015. _this.scene.addGeometry(o);
  28016. });
  28017. this.transformNodes.forEach(function (o) {
  28018. _this.scene.addTransformNode(o);
  28019. });
  28020. this.lensFlareSystems.forEach(function (o) {
  28021. _this.scene.addLensFlareSystem(o);
  28022. });
  28023. this.actionManagers.forEach(function (o) {
  28024. _this.scene.addActionManager(o);
  28025. });
  28026. this.sounds.forEach(function (o) {
  28027. o.play();
  28028. o.autoplay = true;
  28029. _this.scene.mainSoundTrack.AddSound(o);
  28030. });
  28031. this.textures.forEach(function (o) {
  28032. _this.scene.addTexture;
  28033. });
  28034. };
  28035. /**
  28036. * Removes all the assets in the container from the scene
  28037. */
  28038. AssetContainer.prototype.removeAllFromScene = function () {
  28039. var _this = this;
  28040. this.cameras.forEach(function (o) {
  28041. _this.scene.removeCamera(o);
  28042. });
  28043. this.lights.forEach(function (o) {
  28044. _this.scene.removeLight(o);
  28045. });
  28046. this.meshes.forEach(function (o) {
  28047. _this.scene.removeMesh(o);
  28048. });
  28049. this.skeletons.forEach(function (o) {
  28050. _this.scene.removeSkeleton(o);
  28051. });
  28052. this.particleSystems.forEach(function (o) {
  28053. _this.scene.removeParticleSystem(o);
  28054. });
  28055. this.animations.forEach(function (o) {
  28056. _this.scene.removeAnimation(o);
  28057. });
  28058. this.animationGroups.forEach(function (o) {
  28059. _this.scene.removeAnimationGroup(o);
  28060. });
  28061. this.multiMaterials.forEach(function (o) {
  28062. _this.scene.removeMultiMaterial(o);
  28063. });
  28064. this.materials.forEach(function (o) {
  28065. _this.scene.removeMaterial(o);
  28066. });
  28067. this.morphTargetManagers.forEach(function (o) {
  28068. _this.scene.removeMorphTargetManager(o);
  28069. });
  28070. this.geometries.forEach(function (o) {
  28071. _this.scene.removeGeometry(o);
  28072. });
  28073. this.transformNodes.forEach(function (o) {
  28074. _this.scene.removeTransformNode(o);
  28075. });
  28076. this.lensFlareSystems.forEach(function (o) {
  28077. _this.scene.removeLensFlareSystem(o);
  28078. });
  28079. this.actionManagers.forEach(function (o) {
  28080. _this.scene.removeActionManager(o);
  28081. });
  28082. this.sounds.forEach(function (o) {
  28083. o.stop();
  28084. o.autoplay = false;
  28085. _this.scene.mainSoundTrack.RemoveSound(o);
  28086. });
  28087. this.textures.forEach(function (o) {
  28088. _this.scene.removeTexture(o);
  28089. });
  28090. };
  28091. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  28092. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  28093. var asset = sourceAssets_1[_i];
  28094. var move = true;
  28095. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  28096. var keepAsset = keepAssets_1[_a];
  28097. if (asset === keepAsset) {
  28098. move = false;
  28099. break;
  28100. }
  28101. }
  28102. if (move) {
  28103. targetAssets.push(asset);
  28104. }
  28105. }
  28106. };
  28107. /**
  28108. * Removes all the assets contained in the scene and adds them to the container.
  28109. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  28110. */
  28111. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  28112. if (keepAssets === undefined) {
  28113. keepAssets = new KeepAssets();
  28114. }
  28115. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  28116. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  28117. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  28118. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  28119. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  28120. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  28121. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  28122. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  28123. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  28124. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  28125. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  28126. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  28127. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  28128. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  28129. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  28130. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  28131. this.removeAllFromScene();
  28132. };
  28133. return AssetContainer;
  28134. }());
  28135. BABYLON.AssetContainer = AssetContainer;
  28136. })(BABYLON || (BABYLON = {}));
  28137. //# sourceMappingURL=babylon.assetContainer.js.map
  28138. "use strict";
  28139. var BABYLON;
  28140. (function (BABYLON) {
  28141. var Buffer = /** @class */ (function () {
  28142. /**
  28143. * Constructor
  28144. * @param engine the engine
  28145. * @param data the data to use for this buffer
  28146. * @param updatable whether the data is updatable
  28147. * @param stride the stride (optional)
  28148. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  28149. * @param instanced whether the buffer is instanced (optional)
  28150. * @param useBytes set to true if the stride in in bytes (optional)
  28151. */
  28152. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  28153. if (stride === void 0) { stride = 0; }
  28154. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  28155. if (instanced === void 0) { instanced = false; }
  28156. if (useBytes === void 0) { useBytes = false; }
  28157. if (engine instanceof BABYLON.Mesh) {
  28158. this._engine = engine.getScene().getEngine();
  28159. }
  28160. else {
  28161. this._engine = engine;
  28162. }
  28163. this._updatable = updatable;
  28164. this._instanced = instanced;
  28165. this._data = data;
  28166. this.byteStride = useBytes ? stride : stride * 4;
  28167. if (!postponeInternalCreation) {
  28168. this.create();
  28169. }
  28170. }
  28171. /**
  28172. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  28173. * @param kind defines the vertex buffer kind (position, normal, etc.)
  28174. * @param offset defines offset in the buffer (0 by default)
  28175. * @param size defines the size in floats of attributes (position is 3 for instance)
  28176. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  28177. * @param instanced defines if the vertex buffer contains indexed data
  28178. * @param useBytes defines if the offset and stride are in bytes
  28179. * @returns the new vertex buffer
  28180. */
  28181. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  28182. if (useBytes === void 0) { useBytes = false; }
  28183. var byteOffset = useBytes ? offset : offset * 4;
  28184. var byteStride = stride ? (useBytes ? stride : stride * 4) : this.byteStride;
  28185. // a lot of these parameters are ignored as they are overriden by the buffer
  28186. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  28187. };
  28188. // Properties
  28189. Buffer.prototype.isUpdatable = function () {
  28190. return this._updatable;
  28191. };
  28192. Buffer.prototype.getData = function () {
  28193. return this._data;
  28194. };
  28195. Buffer.prototype.getBuffer = function () {
  28196. return this._buffer;
  28197. };
  28198. /**
  28199. * Gets the stride in float32 units (i.e. byte stride / 4).
  28200. * May not be an integer if the byte stride is not divisible by 4.
  28201. * DEPRECATED. Use byteStride instead.
  28202. * @returns the stride in float32 units
  28203. */
  28204. Buffer.prototype.getStrideSize = function () {
  28205. return this.byteStride / 4;
  28206. };
  28207. // Methods
  28208. Buffer.prototype.create = function (data) {
  28209. if (data === void 0) { data = null; }
  28210. if (!data && this._buffer) {
  28211. return; // nothing to do
  28212. }
  28213. data = data || this._data;
  28214. if (!data) {
  28215. return;
  28216. }
  28217. if (!this._buffer) {
  28218. if (this._updatable) {
  28219. this._buffer = this._engine.createDynamicVertexBuffer(data);
  28220. this._data = data;
  28221. }
  28222. else {
  28223. this._buffer = this._engine.createVertexBuffer(data);
  28224. }
  28225. }
  28226. else if (this._updatable) {
  28227. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  28228. this._data = data;
  28229. }
  28230. };
  28231. Buffer.prototype._rebuild = function () {
  28232. this._buffer = null;
  28233. this.create(this._data);
  28234. };
  28235. Buffer.prototype.update = function (data) {
  28236. this.create(data);
  28237. };
  28238. /**
  28239. * Updates the data directly.
  28240. * @param data the new data
  28241. * @param offset the new offset
  28242. * @param vertexCount the vertex count (optional)
  28243. * @param useBytes set to true if the offset is in bytes
  28244. */
  28245. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  28246. if (useBytes === void 0) { useBytes = false; }
  28247. if (!this._buffer) {
  28248. return;
  28249. }
  28250. if (this._updatable) {
  28251. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * 4, (vertexCount ? vertexCount * this.byteStride : undefined));
  28252. this._data = null;
  28253. }
  28254. };
  28255. Buffer.prototype.dispose = function () {
  28256. if (!this._buffer) {
  28257. return;
  28258. }
  28259. if (this._engine._releaseBuffer(this._buffer)) {
  28260. this._buffer = null;
  28261. }
  28262. };
  28263. return Buffer;
  28264. }());
  28265. BABYLON.Buffer = Buffer;
  28266. })(BABYLON || (BABYLON = {}));
  28267. //# sourceMappingURL=babylon.buffer.js.map
  28268. "use strict";
  28269. var BABYLON;
  28270. (function (BABYLON) {
  28271. var VertexBuffer = /** @class */ (function () {
  28272. /**
  28273. * Constructor
  28274. * @param engine the engine
  28275. * @param data the data to use for this vertex buffer
  28276. * @param kind the vertex buffer kind
  28277. * @param updatable whether the data is updatable
  28278. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  28279. * @param stride the stride (optional)
  28280. * @param instanced whether the buffer is instanced (optional)
  28281. * @param offset the offset of the data (optional)
  28282. * @param size the number of components (optional)
  28283. * @param type the type of the component (optional)
  28284. * @param normalized whether the data contains normalized data (optional)
  28285. * @param useBytes set to true if stride and offset are in bytes (optional)
  28286. */
  28287. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  28288. if (normalized === void 0) { normalized = false; }
  28289. if (useBytes === void 0) { useBytes = false; }
  28290. if (data instanceof BABYLON.Buffer) {
  28291. this._buffer = data;
  28292. this._ownsBuffer = false;
  28293. }
  28294. else {
  28295. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  28296. this._ownsBuffer = true;
  28297. }
  28298. this._kind = kind;
  28299. if (type == undefined) {
  28300. var data_1 = this.getData();
  28301. this.type = VertexBuffer.FLOAT;
  28302. if (data_1 instanceof Int8Array)
  28303. this.type = VertexBuffer.BYTE;
  28304. else if (data_1 instanceof Uint8Array)
  28305. this.type = VertexBuffer.UNSIGNED_BYTE;
  28306. else if (data_1 instanceof Int16Array)
  28307. this.type = VertexBuffer.SHORT;
  28308. else if (data_1 instanceof Uint16Array)
  28309. this.type = VertexBuffer.UNSIGNED_SHORT;
  28310. else if (data_1 instanceof Int32Array)
  28311. this.type = VertexBuffer.INT;
  28312. else if (data_1 instanceof Uint32Array)
  28313. this.type = VertexBuffer.UNSIGNED_INT;
  28314. }
  28315. else {
  28316. this.type = type;
  28317. }
  28318. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  28319. if (useBytes) {
  28320. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  28321. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  28322. this.byteOffset = offset || 0;
  28323. }
  28324. else {
  28325. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  28326. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  28327. this.byteOffset = (offset || 0) * typeByteLength;
  28328. }
  28329. this.normalized = normalized;
  28330. this._instanced = instanced !== undefined ? instanced : false;
  28331. this._instanceDivisor = instanced ? 1 : 0;
  28332. }
  28333. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  28334. /**
  28335. * Gets or sets the instance divisor when in instanced mode
  28336. */
  28337. get: function () {
  28338. return this._instanceDivisor;
  28339. },
  28340. set: function (value) {
  28341. this._instanceDivisor = value;
  28342. if (value == 0) {
  28343. this._instanced = false;
  28344. }
  28345. else {
  28346. this._instanced = true;
  28347. }
  28348. },
  28349. enumerable: true,
  28350. configurable: true
  28351. });
  28352. VertexBuffer.prototype._rebuild = function () {
  28353. if (!this._buffer) {
  28354. return;
  28355. }
  28356. this._buffer._rebuild();
  28357. };
  28358. /**
  28359. * Returns the kind of the VertexBuffer (string).
  28360. */
  28361. VertexBuffer.prototype.getKind = function () {
  28362. return this._kind;
  28363. };
  28364. // Properties
  28365. /**
  28366. * Boolean : is the VertexBuffer updatable ?
  28367. */
  28368. VertexBuffer.prototype.isUpdatable = function () {
  28369. return this._buffer.isUpdatable();
  28370. };
  28371. /**
  28372. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  28373. */
  28374. VertexBuffer.prototype.getData = function () {
  28375. return this._buffer.getData();
  28376. };
  28377. /**
  28378. * Returns the WebGLBuffer associated to the VertexBuffer.
  28379. */
  28380. VertexBuffer.prototype.getBuffer = function () {
  28381. return this._buffer.getBuffer();
  28382. };
  28383. /**
  28384. * Returns the stride as a multiple of the type byte length.
  28385. * DEPRECATED. Use byteStride instead.
  28386. */
  28387. VertexBuffer.prototype.getStrideSize = function () {
  28388. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  28389. };
  28390. /**
  28391. * Returns the offset as a multiple of the type byte length.
  28392. * DEPRECATED. Use byteOffset instead.
  28393. */
  28394. VertexBuffer.prototype.getOffset = function () {
  28395. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  28396. };
  28397. /**
  28398. * Returns the number of components per vertex attribute (integer).
  28399. */
  28400. VertexBuffer.prototype.getSize = function () {
  28401. return this._size;
  28402. };
  28403. /**
  28404. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  28405. */
  28406. VertexBuffer.prototype.getIsInstanced = function () {
  28407. return this._instanced;
  28408. };
  28409. /**
  28410. * Returns the instancing divisor, zero for non-instanced (integer).
  28411. */
  28412. VertexBuffer.prototype.getInstanceDivisor = function () {
  28413. return this._instanceDivisor;
  28414. };
  28415. // Methods
  28416. /**
  28417. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  28418. * Returns the created WebGLBuffer.
  28419. */
  28420. VertexBuffer.prototype.create = function (data) {
  28421. return this._buffer.create(data);
  28422. };
  28423. /**
  28424. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  28425. * This function will create a new buffer if the current one is not updatable
  28426. * Returns the updated WebGLBuffer.
  28427. */
  28428. VertexBuffer.prototype.update = function (data) {
  28429. return this._buffer.update(data);
  28430. };
  28431. /**
  28432. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  28433. * Returns the directly updated WebGLBuffer.
  28434. */
  28435. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  28436. return this._buffer.updateDirectly(data, offset);
  28437. };
  28438. /**
  28439. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  28440. */
  28441. VertexBuffer.prototype.dispose = function () {
  28442. if (this._ownsBuffer) {
  28443. this._buffer.dispose();
  28444. }
  28445. };
  28446. /**
  28447. * Enumerates each value of this vertex buffer as numbers.
  28448. * @param count the number of values to enumerate
  28449. * @param callback the callback function called for each value
  28450. */
  28451. VertexBuffer.prototype.forEach = function (count, callback) {
  28452. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  28453. };
  28454. Object.defineProperty(VertexBuffer, "PositionKind", {
  28455. get: function () {
  28456. return VertexBuffer._PositionKind;
  28457. },
  28458. enumerable: true,
  28459. configurable: true
  28460. });
  28461. Object.defineProperty(VertexBuffer, "NormalKind", {
  28462. get: function () {
  28463. return VertexBuffer._NormalKind;
  28464. },
  28465. enumerable: true,
  28466. configurable: true
  28467. });
  28468. Object.defineProperty(VertexBuffer, "TangentKind", {
  28469. get: function () {
  28470. return VertexBuffer._TangentKind;
  28471. },
  28472. enumerable: true,
  28473. configurable: true
  28474. });
  28475. Object.defineProperty(VertexBuffer, "UVKind", {
  28476. get: function () {
  28477. return VertexBuffer._UVKind;
  28478. },
  28479. enumerable: true,
  28480. configurable: true
  28481. });
  28482. Object.defineProperty(VertexBuffer, "UV2Kind", {
  28483. get: function () {
  28484. return VertexBuffer._UV2Kind;
  28485. },
  28486. enumerable: true,
  28487. configurable: true
  28488. });
  28489. Object.defineProperty(VertexBuffer, "UV3Kind", {
  28490. get: function () {
  28491. return VertexBuffer._UV3Kind;
  28492. },
  28493. enumerable: true,
  28494. configurable: true
  28495. });
  28496. Object.defineProperty(VertexBuffer, "UV4Kind", {
  28497. get: function () {
  28498. return VertexBuffer._UV4Kind;
  28499. },
  28500. enumerable: true,
  28501. configurable: true
  28502. });
  28503. Object.defineProperty(VertexBuffer, "UV5Kind", {
  28504. get: function () {
  28505. return VertexBuffer._UV5Kind;
  28506. },
  28507. enumerable: true,
  28508. configurable: true
  28509. });
  28510. Object.defineProperty(VertexBuffer, "UV6Kind", {
  28511. get: function () {
  28512. return VertexBuffer._UV6Kind;
  28513. },
  28514. enumerable: true,
  28515. configurable: true
  28516. });
  28517. Object.defineProperty(VertexBuffer, "ColorKind", {
  28518. get: function () {
  28519. return VertexBuffer._ColorKind;
  28520. },
  28521. enumerable: true,
  28522. configurable: true
  28523. });
  28524. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  28525. get: function () {
  28526. return VertexBuffer._MatricesIndicesKind;
  28527. },
  28528. enumerable: true,
  28529. configurable: true
  28530. });
  28531. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  28532. get: function () {
  28533. return VertexBuffer._MatricesWeightsKind;
  28534. },
  28535. enumerable: true,
  28536. configurable: true
  28537. });
  28538. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  28539. get: function () {
  28540. return VertexBuffer._MatricesIndicesExtraKind;
  28541. },
  28542. enumerable: true,
  28543. configurable: true
  28544. });
  28545. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  28546. get: function () {
  28547. return VertexBuffer._MatricesWeightsExtraKind;
  28548. },
  28549. enumerable: true,
  28550. configurable: true
  28551. });
  28552. /**
  28553. * Deduces the stride given a kind.
  28554. * @param kind The kind string to deduce
  28555. * @returns The deduced stride
  28556. */
  28557. VertexBuffer.DeduceStride = function (kind) {
  28558. switch (kind) {
  28559. case VertexBuffer.UVKind:
  28560. case VertexBuffer.UV2Kind:
  28561. case VertexBuffer.UV3Kind:
  28562. case VertexBuffer.UV4Kind:
  28563. case VertexBuffer.UV5Kind:
  28564. case VertexBuffer.UV6Kind:
  28565. return 2;
  28566. case VertexBuffer.NormalKind:
  28567. case VertexBuffer.PositionKind:
  28568. return 3;
  28569. case VertexBuffer.ColorKind:
  28570. case VertexBuffer.MatricesIndicesKind:
  28571. case VertexBuffer.MatricesIndicesExtraKind:
  28572. case VertexBuffer.MatricesWeightsKind:
  28573. case VertexBuffer.MatricesWeightsExtraKind:
  28574. case VertexBuffer.TangentKind:
  28575. return 4;
  28576. default:
  28577. throw new Error("Invalid kind '" + kind + "'");
  28578. }
  28579. };
  28580. /**
  28581. * Gets the byte length of the given type.
  28582. * @param type the type
  28583. * @returns the number of bytes
  28584. */
  28585. VertexBuffer.GetTypeByteLength = function (type) {
  28586. switch (type) {
  28587. case VertexBuffer.BYTE:
  28588. case VertexBuffer.UNSIGNED_BYTE:
  28589. return 1;
  28590. case VertexBuffer.SHORT:
  28591. case VertexBuffer.UNSIGNED_SHORT:
  28592. return 2;
  28593. case VertexBuffer.INT:
  28594. case VertexBuffer.FLOAT:
  28595. return 4;
  28596. default:
  28597. throw new Error("Invalid type '" + type + "'");
  28598. }
  28599. };
  28600. /**
  28601. * Enumerates each value of the given parameters as numbers.
  28602. * @param data the data to enumerate
  28603. * @param byteOffset the byte offset of the data
  28604. * @param byteStride the byte stride of the data
  28605. * @param componentCount the number of components per element
  28606. * @param componentType the type of the component
  28607. * @param count the total number of components
  28608. * @param normalized whether the data is normalized
  28609. * @param callback the callback function called for each value
  28610. */
  28611. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  28612. if (data instanceof Array) {
  28613. var offset = byteOffset / 4;
  28614. var stride = byteStride / 4;
  28615. for (var index = 0; index < count; index += componentCount) {
  28616. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  28617. callback(data[offset + componentIndex], index + componentIndex);
  28618. }
  28619. offset += stride;
  28620. }
  28621. }
  28622. else {
  28623. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  28624. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  28625. for (var index = 0; index < count; index += componentCount) {
  28626. var componentByteOffset = byteOffset;
  28627. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  28628. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  28629. callback(value, index + componentIndex);
  28630. componentByteOffset += componentByteLength;
  28631. }
  28632. byteOffset += byteStride;
  28633. }
  28634. }
  28635. };
  28636. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  28637. switch (type) {
  28638. case VertexBuffer.BYTE: {
  28639. var value = dataView.getInt8(byteOffset);
  28640. if (normalized) {
  28641. value = (value + 0.5) / 127.5;
  28642. }
  28643. return value;
  28644. }
  28645. case VertexBuffer.UNSIGNED_BYTE: {
  28646. var value = dataView.getUint8(byteOffset);
  28647. if (normalized) {
  28648. value = value / 255;
  28649. }
  28650. return value;
  28651. }
  28652. case VertexBuffer.SHORT: {
  28653. var value = dataView.getInt16(byteOffset, true);
  28654. if (normalized) {
  28655. value = (value + 0.5) / 16383.5;
  28656. }
  28657. return value;
  28658. }
  28659. case VertexBuffer.UNSIGNED_SHORT: {
  28660. var value = dataView.getUint16(byteOffset, true);
  28661. if (normalized) {
  28662. value = value / 65535;
  28663. }
  28664. return value;
  28665. }
  28666. case VertexBuffer.FLOAT: {
  28667. return dataView.getFloat32(byteOffset, true);
  28668. }
  28669. default: {
  28670. throw new Error("Invalid component type " + type);
  28671. }
  28672. }
  28673. };
  28674. /**
  28675. * The byte type.
  28676. */
  28677. VertexBuffer.BYTE = 5120;
  28678. /**
  28679. * The unsigned byte type.
  28680. */
  28681. VertexBuffer.UNSIGNED_BYTE = 5121;
  28682. /**
  28683. * The short type.
  28684. */
  28685. VertexBuffer.SHORT = 5122;
  28686. /**
  28687. * The unsigned short type.
  28688. */
  28689. VertexBuffer.UNSIGNED_SHORT = 5123;
  28690. /**
  28691. * The integer type.
  28692. */
  28693. VertexBuffer.INT = 5124;
  28694. /**
  28695. * The unsigned integer type.
  28696. */
  28697. VertexBuffer.UNSIGNED_INT = 5125;
  28698. /**
  28699. * The float type.
  28700. */
  28701. VertexBuffer.FLOAT = 5126;
  28702. // Enums
  28703. VertexBuffer._PositionKind = "position";
  28704. VertexBuffer._NormalKind = "normal";
  28705. VertexBuffer._TangentKind = "tangent";
  28706. VertexBuffer._UVKind = "uv";
  28707. VertexBuffer._UV2Kind = "uv2";
  28708. VertexBuffer._UV3Kind = "uv3";
  28709. VertexBuffer._UV4Kind = "uv4";
  28710. VertexBuffer._UV5Kind = "uv5";
  28711. VertexBuffer._UV6Kind = "uv6";
  28712. VertexBuffer._ColorKind = "color";
  28713. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  28714. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  28715. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  28716. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  28717. return VertexBuffer;
  28718. }());
  28719. BABYLON.VertexBuffer = VertexBuffer;
  28720. })(BABYLON || (BABYLON = {}));
  28721. //# sourceMappingURL=babylon.vertexBuffer.js.map
  28722. "use strict";
  28723. var BABYLON;
  28724. (function (BABYLON) {
  28725. /**
  28726. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  28727. */
  28728. var DummyInternalTextureTracker = /** @class */ (function () {
  28729. function DummyInternalTextureTracker() {
  28730. /**
  28731. * Gets or set the previous tracker in the list
  28732. */
  28733. this.previous = null;
  28734. /**
  28735. * Gets or set the next tracker in the list
  28736. */
  28737. this.next = null;
  28738. }
  28739. return DummyInternalTextureTracker;
  28740. }());
  28741. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  28742. })(BABYLON || (BABYLON = {}));
  28743. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  28744. "use strict";
  28745. var BABYLON;
  28746. (function (BABYLON) {
  28747. /**
  28748. * Class used to store data associated with WebGL texture data for the engine
  28749. * This class should not be used directly
  28750. */
  28751. var InternalTexture = /** @class */ (function () {
  28752. /**
  28753. * Creates a new InternalTexture
  28754. * @param engine defines the engine to use
  28755. * @param dataSource defines the type of data that will be used
  28756. */
  28757. function InternalTexture(engine, dataSource) {
  28758. /**
  28759. * Observable called when the texture is loaded
  28760. */
  28761. this.onLoadedObservable = new BABYLON.Observable();
  28762. /**
  28763. * Gets or set the previous tracker in the list
  28764. */
  28765. this.previous = null;
  28766. /**
  28767. * Gets or set the next tracker in the list
  28768. */
  28769. this.next = null;
  28770. // Private
  28771. /** @ignore */
  28772. this._initialSlot = -1;
  28773. /** @ignore */
  28774. this._designatedSlot = -1;
  28775. /** @ignore */
  28776. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  28777. /** @ignore */
  28778. this._comparisonFunction = 0;
  28779. /** @ignore */
  28780. this._references = 1;
  28781. this._engine = engine;
  28782. this._dataSource = dataSource;
  28783. this._webGLTexture = engine._createTexture();
  28784. }
  28785. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  28786. /**
  28787. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  28788. */
  28789. get: function () {
  28790. return this._dataSource;
  28791. },
  28792. enumerable: true,
  28793. configurable: true
  28794. });
  28795. /**
  28796. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  28797. */
  28798. InternalTexture.prototype.incrementReferences = function () {
  28799. this._references++;
  28800. };
  28801. /**
  28802. * Change the size of the texture (not the size of the content)
  28803. * @param width defines the new width
  28804. * @param height defines the new height
  28805. * @param depth defines the new depth (1 by default)
  28806. */
  28807. InternalTexture.prototype.updateSize = function (width, height, depth) {
  28808. if (depth === void 0) { depth = 1; }
  28809. this.width = width;
  28810. this.height = height;
  28811. this.depth = depth;
  28812. this.baseWidth = width;
  28813. this.baseHeight = height;
  28814. this.baseDepth = depth;
  28815. this._size = width * height * depth;
  28816. };
  28817. /** @ignore */
  28818. InternalTexture.prototype._rebuild = function () {
  28819. var _this = this;
  28820. var proxy;
  28821. this.isReady = false;
  28822. this._cachedCoordinatesMode = null;
  28823. this._cachedWrapU = null;
  28824. this._cachedWrapV = null;
  28825. this._cachedAnisotropicFilteringLevel = null;
  28826. switch (this._dataSource) {
  28827. case InternalTexture.DATASOURCE_TEMP:
  28828. return;
  28829. case InternalTexture.DATASOURCE_URL:
  28830. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  28831. _this.isReady = true;
  28832. }, null, this._buffer, undefined, this.format);
  28833. proxy._swapAndDie(this);
  28834. return;
  28835. case InternalTexture.DATASOURCE_RAW:
  28836. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  28837. proxy._swapAndDie(this);
  28838. this.isReady = true;
  28839. return;
  28840. case InternalTexture.DATASOURCE_RAW3D:
  28841. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  28842. proxy._swapAndDie(this);
  28843. this.isReady = true;
  28844. return;
  28845. case InternalTexture.DATASOURCE_DYNAMIC:
  28846. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  28847. proxy._swapAndDie(this);
  28848. // The engine will make sure to update content so no need to flag it as isReady = true
  28849. return;
  28850. case InternalTexture.DATASOURCE_RENDERTARGET:
  28851. var options = new BABYLON.RenderTargetCreationOptions();
  28852. options.generateDepthBuffer = this._generateDepthBuffer;
  28853. options.generateMipMaps = this.generateMipMaps;
  28854. options.generateStencilBuffer = this._generateStencilBuffer;
  28855. options.samplingMode = this.samplingMode;
  28856. options.type = this.type;
  28857. if (this.isCube) {
  28858. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  28859. }
  28860. else {
  28861. var size = {
  28862. width: this.width,
  28863. height: this.height
  28864. };
  28865. proxy = this._engine.createRenderTargetTexture(size, options);
  28866. }
  28867. proxy._swapAndDie(this);
  28868. this.isReady = true;
  28869. return;
  28870. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  28871. var depthTextureOptions = {
  28872. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  28873. comparisonFunction: this._comparisonFunction,
  28874. generateStencil: this._generateStencilBuffer,
  28875. isCube: this.isCube
  28876. };
  28877. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  28878. proxy._swapAndDie(this);
  28879. this.isReady = true;
  28880. return;
  28881. case InternalTexture.DATASOURCE_CUBE:
  28882. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  28883. _this.isReady = true;
  28884. }, null, this.format, this._extension);
  28885. proxy._swapAndDie(this);
  28886. return;
  28887. case InternalTexture.DATASOURCE_CUBERAW:
  28888. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  28889. proxy._swapAndDie(this);
  28890. this.isReady = true;
  28891. return;
  28892. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  28893. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  28894. if (proxy) {
  28895. proxy._swapAndDie(_this);
  28896. }
  28897. _this.isReady = true;
  28898. }, null, this.format, this._extension);
  28899. return;
  28900. }
  28901. };
  28902. InternalTexture.prototype._swapAndDie = function (target) {
  28903. target._webGLTexture = this._webGLTexture;
  28904. if (this._framebuffer) {
  28905. target._framebuffer = this._framebuffer;
  28906. }
  28907. if (this._depthStencilBuffer) {
  28908. target._depthStencilBuffer = this._depthStencilBuffer;
  28909. }
  28910. if (this._lodTextureHigh) {
  28911. if (target._lodTextureHigh) {
  28912. target._lodTextureHigh.dispose();
  28913. }
  28914. target._lodTextureHigh = this._lodTextureHigh;
  28915. }
  28916. if (this._lodTextureMid) {
  28917. if (target._lodTextureMid) {
  28918. target._lodTextureMid.dispose();
  28919. }
  28920. target._lodTextureMid = this._lodTextureMid;
  28921. }
  28922. if (this._lodTextureLow) {
  28923. if (target._lodTextureLow) {
  28924. target._lodTextureLow.dispose();
  28925. }
  28926. target._lodTextureLow = this._lodTextureLow;
  28927. }
  28928. var cache = this._engine.getLoadedTexturesCache();
  28929. var index = cache.indexOf(this);
  28930. if (index !== -1) {
  28931. cache.splice(index, 1);
  28932. }
  28933. };
  28934. /**
  28935. * Dispose the current allocated resources
  28936. */
  28937. InternalTexture.prototype.dispose = function () {
  28938. if (!this._webGLTexture) {
  28939. return;
  28940. }
  28941. this._references--;
  28942. if (this._references === 0) {
  28943. this._engine._releaseTexture(this);
  28944. this._webGLTexture = null;
  28945. this.previous = null;
  28946. this.next = null;
  28947. }
  28948. };
  28949. /**
  28950. * The source of the texture data is unknown
  28951. */
  28952. InternalTexture.DATASOURCE_UNKNOWN = 0;
  28953. /**
  28954. * Texture data comes from an URL
  28955. */
  28956. InternalTexture.DATASOURCE_URL = 1;
  28957. /**
  28958. * Texture data is only used for temporary storage
  28959. */
  28960. InternalTexture.DATASOURCE_TEMP = 2;
  28961. /**
  28962. * Texture data comes from raw data (ArrayBuffer)
  28963. */
  28964. InternalTexture.DATASOURCE_RAW = 3;
  28965. /**
  28966. * Texture content is dynamic (video or dynamic texture)
  28967. */
  28968. InternalTexture.DATASOURCE_DYNAMIC = 4;
  28969. /**
  28970. * Texture content is generated by rendering to it
  28971. */
  28972. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  28973. /**
  28974. * Texture content is part of a multi render target process
  28975. */
  28976. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  28977. /**
  28978. * Texture data comes from a cube data file
  28979. */
  28980. InternalTexture.DATASOURCE_CUBE = 7;
  28981. /**
  28982. * Texture data comes from a raw cube data
  28983. */
  28984. InternalTexture.DATASOURCE_CUBERAW = 8;
  28985. /**
  28986. * Texture data come from a prefiltered cube data file
  28987. */
  28988. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  28989. /**
  28990. * Texture content is raw 3D data
  28991. */
  28992. InternalTexture.DATASOURCE_RAW3D = 10;
  28993. /**
  28994. * Texture content is a depth texture
  28995. */
  28996. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  28997. return InternalTexture;
  28998. }());
  28999. BABYLON.InternalTexture = InternalTexture;
  29000. })(BABYLON || (BABYLON = {}));
  29001. //# sourceMappingURL=babylon.internalTexture.js.map
  29002. "use strict";
  29003. var BABYLON;
  29004. (function (BABYLON) {
  29005. var BaseTexture = /** @class */ (function () {
  29006. function BaseTexture(scene) {
  29007. this._hasAlpha = false;
  29008. this.getAlphaFromRGB = false;
  29009. this.level = 1;
  29010. this.coordinatesIndex = 0;
  29011. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  29012. /**
  29013. * | Value | Type | Description |
  29014. * | ----- | ------------------ | ----------- |
  29015. * | 0 | CLAMP_ADDRESSMODE | |
  29016. * | 1 | WRAP_ADDRESSMODE | |
  29017. * | 2 | MIRROR_ADDRESSMODE | |
  29018. */
  29019. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29020. /**
  29021. * | Value | Type | Description |
  29022. * | ----- | ------------------ | ----------- |
  29023. * | 0 | CLAMP_ADDRESSMODE | |
  29024. * | 1 | WRAP_ADDRESSMODE | |
  29025. * | 2 | MIRROR_ADDRESSMODE | |
  29026. */
  29027. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29028. /**
  29029. * | Value | Type | Description |
  29030. * | ----- | ------------------ | ----------- |
  29031. * | 0 | CLAMP_ADDRESSMODE | |
  29032. * | 1 | WRAP_ADDRESSMODE | |
  29033. * | 2 | MIRROR_ADDRESSMODE | |
  29034. */
  29035. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  29036. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  29037. this.isCube = false;
  29038. this.is3D = false;
  29039. this.gammaSpace = true;
  29040. this.invertZ = false;
  29041. this.lodLevelInAlpha = false;
  29042. this.lodGenerationOffset = 0.0;
  29043. this.lodGenerationScale = 0.8;
  29044. this.isRenderTarget = false;
  29045. this.animations = new Array();
  29046. /**
  29047. * An event triggered when the texture is disposed.
  29048. */
  29049. this.onDisposeObservable = new BABYLON.Observable();
  29050. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29051. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29052. if (this._scene) {
  29053. this._scene.textures.push(this);
  29054. }
  29055. this._uid = null;
  29056. }
  29057. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  29058. get: function () {
  29059. return this._hasAlpha;
  29060. },
  29061. set: function (value) {
  29062. if (this._hasAlpha === value) {
  29063. return;
  29064. }
  29065. this._hasAlpha = value;
  29066. if (this._scene) {
  29067. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  29068. }
  29069. },
  29070. enumerable: true,
  29071. configurable: true
  29072. });
  29073. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  29074. get: function () {
  29075. return this._coordinatesMode;
  29076. },
  29077. /**
  29078. * How a texture is mapped.
  29079. *
  29080. * | Value | Type | Description |
  29081. * | ----- | ----------------------------------- | ----------- |
  29082. * | 0 | EXPLICIT_MODE | |
  29083. * | 1 | SPHERICAL_MODE | |
  29084. * | 2 | PLANAR_MODE | |
  29085. * | 3 | CUBIC_MODE | |
  29086. * | 4 | PROJECTION_MODE | |
  29087. * | 5 | SKYBOX_MODE | |
  29088. * | 6 | INVCUBIC_MODE | |
  29089. * | 7 | EQUIRECTANGULAR_MODE | |
  29090. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  29091. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  29092. */
  29093. set: function (value) {
  29094. if (this._coordinatesMode === value) {
  29095. return;
  29096. }
  29097. this._coordinatesMode = value;
  29098. if (this._scene) {
  29099. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29100. }
  29101. },
  29102. enumerable: true,
  29103. configurable: true
  29104. });
  29105. Object.defineProperty(BaseTexture.prototype, "uid", {
  29106. get: function () {
  29107. if (!this._uid) {
  29108. this._uid = BABYLON.Tools.RandomId();
  29109. }
  29110. return this._uid;
  29111. },
  29112. enumerable: true,
  29113. configurable: true
  29114. });
  29115. BaseTexture.prototype.toString = function () {
  29116. return this.name;
  29117. };
  29118. BaseTexture.prototype.getClassName = function () {
  29119. return "BaseTexture";
  29120. };
  29121. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  29122. set: function (callback) {
  29123. if (this._onDisposeObserver) {
  29124. this.onDisposeObservable.remove(this._onDisposeObserver);
  29125. }
  29126. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29127. },
  29128. enumerable: true,
  29129. configurable: true
  29130. });
  29131. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  29132. get: function () {
  29133. return true;
  29134. },
  29135. enumerable: true,
  29136. configurable: true
  29137. });
  29138. BaseTexture.prototype.getScene = function () {
  29139. return this._scene;
  29140. };
  29141. BaseTexture.prototype.getTextureMatrix = function () {
  29142. return BABYLON.Matrix.IdentityReadOnly;
  29143. };
  29144. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  29145. return BABYLON.Matrix.IdentityReadOnly;
  29146. };
  29147. BaseTexture.prototype.getInternalTexture = function () {
  29148. return this._texture;
  29149. };
  29150. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  29151. return !this.isBlocking || this.isReady();
  29152. };
  29153. BaseTexture.prototype.isReady = function () {
  29154. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  29155. this.delayLoad();
  29156. return false;
  29157. }
  29158. if (this._texture) {
  29159. return this._texture.isReady;
  29160. }
  29161. return false;
  29162. };
  29163. BaseTexture.prototype.getSize = function () {
  29164. if (this._texture && this._texture.width) {
  29165. return new BABYLON.Size(this._texture.width, this._texture.height);
  29166. }
  29167. if (this._texture && this._texture._size) {
  29168. return new BABYLON.Size(this._texture._size, this._texture._size);
  29169. }
  29170. return BABYLON.Size.Zero();
  29171. };
  29172. BaseTexture.prototype.getBaseSize = function () {
  29173. if (!this.isReady() || !this._texture)
  29174. return BABYLON.Size.Zero();
  29175. if (this._texture._size) {
  29176. return new BABYLON.Size(this._texture._size, this._texture._size);
  29177. }
  29178. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  29179. };
  29180. BaseTexture.prototype.scale = function (ratio) {
  29181. };
  29182. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  29183. get: function () {
  29184. return false;
  29185. },
  29186. enumerable: true,
  29187. configurable: true
  29188. });
  29189. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  29190. if (!this._scene) {
  29191. return null;
  29192. }
  29193. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  29194. for (var index = 0; index < texturesCache.length; index++) {
  29195. var texturesCacheEntry = texturesCache[index];
  29196. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  29197. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  29198. texturesCacheEntry.incrementReferences();
  29199. return texturesCacheEntry;
  29200. }
  29201. }
  29202. }
  29203. return null;
  29204. };
  29205. BaseTexture.prototype._rebuild = function () {
  29206. };
  29207. BaseTexture.prototype.delayLoad = function () {
  29208. };
  29209. BaseTexture.prototype.clone = function () {
  29210. return null;
  29211. };
  29212. Object.defineProperty(BaseTexture.prototype, "textureType", {
  29213. get: function () {
  29214. if (!this._texture) {
  29215. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  29216. }
  29217. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  29218. },
  29219. enumerable: true,
  29220. configurable: true
  29221. });
  29222. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  29223. get: function () {
  29224. if (!this._texture) {
  29225. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  29226. }
  29227. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  29228. },
  29229. enumerable: true,
  29230. configurable: true
  29231. });
  29232. BaseTexture.prototype.readPixels = function (faceIndex) {
  29233. if (faceIndex === void 0) { faceIndex = 0; }
  29234. if (!this._texture) {
  29235. return null;
  29236. }
  29237. var size = this.getSize();
  29238. var scene = this.getScene();
  29239. if (!scene) {
  29240. return null;
  29241. }
  29242. var engine = scene.getEngine();
  29243. if (this._texture.isCube) {
  29244. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  29245. }
  29246. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  29247. };
  29248. BaseTexture.prototype.releaseInternalTexture = function () {
  29249. if (this._texture) {
  29250. this._texture.dispose();
  29251. this._texture = null;
  29252. }
  29253. };
  29254. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  29255. get: function () {
  29256. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  29257. return null;
  29258. }
  29259. if (!this._texture._sphericalPolynomial) {
  29260. this._texture._sphericalPolynomial =
  29261. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  29262. }
  29263. return this._texture._sphericalPolynomial;
  29264. },
  29265. set: function (value) {
  29266. if (this._texture) {
  29267. this._texture._sphericalPolynomial = value;
  29268. }
  29269. },
  29270. enumerable: true,
  29271. configurable: true
  29272. });
  29273. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  29274. get: function () {
  29275. if (this._texture) {
  29276. return this._texture._lodTextureHigh;
  29277. }
  29278. return null;
  29279. },
  29280. enumerable: true,
  29281. configurable: true
  29282. });
  29283. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  29284. get: function () {
  29285. if (this._texture) {
  29286. return this._texture._lodTextureMid;
  29287. }
  29288. return null;
  29289. },
  29290. enumerable: true,
  29291. configurable: true
  29292. });
  29293. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  29294. get: function () {
  29295. if (this._texture) {
  29296. return this._texture._lodTextureLow;
  29297. }
  29298. return null;
  29299. },
  29300. enumerable: true,
  29301. configurable: true
  29302. });
  29303. BaseTexture.prototype.dispose = function () {
  29304. if (!this._scene) {
  29305. return;
  29306. }
  29307. // Animations
  29308. this._scene.stopAnimation(this);
  29309. // Remove from scene
  29310. this._scene._removePendingData(this);
  29311. var index = this._scene.textures.indexOf(this);
  29312. if (index >= 0) {
  29313. this._scene.textures.splice(index, 1);
  29314. }
  29315. if (this._texture === undefined) {
  29316. return;
  29317. }
  29318. // Release
  29319. this.releaseInternalTexture();
  29320. // Callback
  29321. this.onDisposeObservable.notifyObservers(this);
  29322. this.onDisposeObservable.clear();
  29323. };
  29324. BaseTexture.prototype.serialize = function () {
  29325. if (!this.name) {
  29326. return null;
  29327. }
  29328. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  29329. // Animations
  29330. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29331. return serializationObject;
  29332. };
  29333. BaseTexture.WhenAllReady = function (textures, callback) {
  29334. var numRemaining = textures.length;
  29335. if (numRemaining === 0) {
  29336. callback();
  29337. return;
  29338. }
  29339. var _loop_1 = function () {
  29340. texture = textures[i];
  29341. if (texture.isReady()) {
  29342. if (--numRemaining === 0) {
  29343. callback();
  29344. }
  29345. }
  29346. else {
  29347. onLoadObservable = texture.onLoadObservable;
  29348. var onLoadCallback_1 = function () {
  29349. onLoadObservable.removeCallback(onLoadCallback_1);
  29350. if (--numRemaining === 0) {
  29351. callback();
  29352. }
  29353. };
  29354. onLoadObservable.add(onLoadCallback_1);
  29355. }
  29356. };
  29357. var texture, onLoadObservable;
  29358. for (var i = 0; i < textures.length; i++) {
  29359. _loop_1();
  29360. }
  29361. };
  29362. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  29363. __decorate([
  29364. BABYLON.serialize()
  29365. ], BaseTexture.prototype, "name", void 0);
  29366. __decorate([
  29367. BABYLON.serialize("hasAlpha")
  29368. ], BaseTexture.prototype, "_hasAlpha", void 0);
  29369. __decorate([
  29370. BABYLON.serialize()
  29371. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  29372. __decorate([
  29373. BABYLON.serialize()
  29374. ], BaseTexture.prototype, "level", void 0);
  29375. __decorate([
  29376. BABYLON.serialize()
  29377. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  29378. __decorate([
  29379. BABYLON.serialize("coordinatesMode")
  29380. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  29381. __decorate([
  29382. BABYLON.serialize()
  29383. ], BaseTexture.prototype, "wrapU", void 0);
  29384. __decorate([
  29385. BABYLON.serialize()
  29386. ], BaseTexture.prototype, "wrapV", void 0);
  29387. __decorate([
  29388. BABYLON.serialize()
  29389. ], BaseTexture.prototype, "wrapR", void 0);
  29390. __decorate([
  29391. BABYLON.serialize()
  29392. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  29393. __decorate([
  29394. BABYLON.serialize()
  29395. ], BaseTexture.prototype, "isCube", void 0);
  29396. __decorate([
  29397. BABYLON.serialize()
  29398. ], BaseTexture.prototype, "is3D", void 0);
  29399. __decorate([
  29400. BABYLON.serialize()
  29401. ], BaseTexture.prototype, "gammaSpace", void 0);
  29402. __decorate([
  29403. BABYLON.serialize()
  29404. ], BaseTexture.prototype, "invertZ", void 0);
  29405. __decorate([
  29406. BABYLON.serialize()
  29407. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  29408. __decorate([
  29409. BABYLON.serialize()
  29410. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  29411. __decorate([
  29412. BABYLON.serialize()
  29413. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  29414. __decorate([
  29415. BABYLON.serialize()
  29416. ], BaseTexture.prototype, "isRenderTarget", void 0);
  29417. return BaseTexture;
  29418. }());
  29419. BABYLON.BaseTexture = BaseTexture;
  29420. })(BABYLON || (BABYLON = {}));
  29421. //# sourceMappingURL=babylon.baseTexture.js.map
  29422. "use strict";
  29423. var BABYLON;
  29424. (function (BABYLON) {
  29425. var Texture = /** @class */ (function (_super) {
  29426. __extends(Texture, _super);
  29427. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  29428. if (noMipmap === void 0) { noMipmap = false; }
  29429. if (invertY === void 0) { invertY = true; }
  29430. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  29431. if (onLoad === void 0) { onLoad = null; }
  29432. if (onError === void 0) { onError = null; }
  29433. if (buffer === void 0) { buffer = null; }
  29434. if (deleteBuffer === void 0) { deleteBuffer = false; }
  29435. var _this = _super.call(this, scene) || this;
  29436. _this.uOffset = 0;
  29437. _this.vOffset = 0;
  29438. _this.uScale = 1.0;
  29439. _this.vScale = 1.0;
  29440. _this.uAng = 0;
  29441. _this.vAng = 0;
  29442. _this.wAng = 0;
  29443. _this._isBlocking = true;
  29444. _this.name = url || "";
  29445. _this.url = url;
  29446. _this._noMipmap = noMipmap;
  29447. _this._invertY = invertY;
  29448. _this._samplingMode = samplingMode;
  29449. _this._buffer = buffer;
  29450. _this._deleteBuffer = deleteBuffer;
  29451. if (format) {
  29452. _this._format = format;
  29453. }
  29454. scene = _this.getScene();
  29455. if (!scene) {
  29456. return _this;
  29457. }
  29458. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  29459. var load = function () {
  29460. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  29461. _this.onLoadObservable.notifyObservers(_this);
  29462. }
  29463. if (onLoad) {
  29464. onLoad();
  29465. }
  29466. if (!_this.isBlocking && scene) {
  29467. scene.resetCachedMaterial();
  29468. }
  29469. };
  29470. if (!_this.url) {
  29471. _this._delayedOnLoad = load;
  29472. _this._delayedOnError = onError;
  29473. return _this;
  29474. }
  29475. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  29476. if (!_this._texture) {
  29477. if (!scene.useDelayedTextureLoading) {
  29478. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  29479. if (deleteBuffer) {
  29480. delete _this._buffer;
  29481. }
  29482. }
  29483. else {
  29484. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29485. _this._delayedOnLoad = load;
  29486. _this._delayedOnError = onError;
  29487. }
  29488. }
  29489. else {
  29490. if (_this._texture.isReady) {
  29491. BABYLON.Tools.SetImmediate(function () { return load(); });
  29492. }
  29493. else {
  29494. _this._texture.onLoadedObservable.add(load);
  29495. }
  29496. }
  29497. return _this;
  29498. }
  29499. Object.defineProperty(Texture.prototype, "noMipmap", {
  29500. get: function () {
  29501. return this._noMipmap;
  29502. },
  29503. enumerable: true,
  29504. configurable: true
  29505. });
  29506. Object.defineProperty(Texture.prototype, "isBlocking", {
  29507. get: function () {
  29508. return this._isBlocking;
  29509. },
  29510. set: function (value) {
  29511. this._isBlocking = value;
  29512. },
  29513. enumerable: true,
  29514. configurable: true
  29515. });
  29516. Object.defineProperty(Texture.prototype, "samplingMode", {
  29517. get: function () {
  29518. return this._samplingMode;
  29519. },
  29520. enumerable: true,
  29521. configurable: true
  29522. });
  29523. Texture.prototype.updateURL = function (url) {
  29524. this.url = url;
  29525. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29526. this.delayLoad();
  29527. };
  29528. Texture.prototype.delayLoad = function () {
  29529. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  29530. return;
  29531. }
  29532. var scene = this.getScene();
  29533. if (!scene) {
  29534. return;
  29535. }
  29536. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  29537. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  29538. if (!this._texture) {
  29539. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  29540. if (this._deleteBuffer) {
  29541. delete this._buffer;
  29542. }
  29543. }
  29544. else {
  29545. if (this._delayedOnLoad) {
  29546. if (this._texture.isReady) {
  29547. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  29548. }
  29549. else {
  29550. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  29551. }
  29552. }
  29553. }
  29554. this._delayedOnLoad = null;
  29555. this._delayedOnError = null;
  29556. };
  29557. Texture.prototype.updateSamplingMode = function (samplingMode) {
  29558. if (!this._texture) {
  29559. return;
  29560. }
  29561. var scene = this.getScene();
  29562. if (!scene) {
  29563. return;
  29564. }
  29565. this._samplingMode = samplingMode;
  29566. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  29567. };
  29568. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  29569. x *= this.uScale;
  29570. y *= this.vScale;
  29571. x -= 0.5 * this.uScale;
  29572. y -= 0.5 * this.vScale;
  29573. z -= 0.5;
  29574. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  29575. t.x += 0.5 * this.uScale + this.uOffset;
  29576. t.y += 0.5 * this.vScale + this.vOffset;
  29577. t.z += 0.5;
  29578. };
  29579. Texture.prototype.getTextureMatrix = function () {
  29580. var _this = this;
  29581. if (this.uOffset === this._cachedUOffset &&
  29582. this.vOffset === this._cachedVOffset &&
  29583. this.uScale === this._cachedUScale &&
  29584. this.vScale === this._cachedVScale &&
  29585. this.uAng === this._cachedUAng &&
  29586. this.vAng === this._cachedVAng &&
  29587. this.wAng === this._cachedWAng) {
  29588. return this._cachedTextureMatrix;
  29589. }
  29590. this._cachedUOffset = this.uOffset;
  29591. this._cachedVOffset = this.vOffset;
  29592. this._cachedUScale = this.uScale;
  29593. this._cachedVScale = this.vScale;
  29594. this._cachedUAng = this.uAng;
  29595. this._cachedVAng = this.vAng;
  29596. this._cachedWAng = this.wAng;
  29597. if (!this._cachedTextureMatrix) {
  29598. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  29599. this._rowGenerationMatrix = new BABYLON.Matrix();
  29600. this._t0 = BABYLON.Vector3.Zero();
  29601. this._t1 = BABYLON.Vector3.Zero();
  29602. this._t2 = BABYLON.Vector3.Zero();
  29603. }
  29604. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  29605. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  29606. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  29607. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  29608. this._t1.subtractInPlace(this._t0);
  29609. this._t2.subtractInPlace(this._t0);
  29610. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  29611. this._cachedTextureMatrix.m[0] = this._t1.x;
  29612. this._cachedTextureMatrix.m[1] = this._t1.y;
  29613. this._cachedTextureMatrix.m[2] = this._t1.z;
  29614. this._cachedTextureMatrix.m[4] = this._t2.x;
  29615. this._cachedTextureMatrix.m[5] = this._t2.y;
  29616. this._cachedTextureMatrix.m[6] = this._t2.z;
  29617. this._cachedTextureMatrix.m[8] = this._t0.x;
  29618. this._cachedTextureMatrix.m[9] = this._t0.y;
  29619. this._cachedTextureMatrix.m[10] = this._t0.z;
  29620. var scene = this.getScene();
  29621. if (!scene) {
  29622. return this._cachedTextureMatrix;
  29623. }
  29624. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  29625. return mat.hasTexture(_this);
  29626. });
  29627. return this._cachedTextureMatrix;
  29628. };
  29629. Texture.prototype.getReflectionTextureMatrix = function () {
  29630. var _this = this;
  29631. var scene = this.getScene();
  29632. if (!scene) {
  29633. return this._cachedTextureMatrix;
  29634. }
  29635. if (this.uOffset === this._cachedUOffset &&
  29636. this.vOffset === this._cachedVOffset &&
  29637. this.uScale === this._cachedUScale &&
  29638. this.vScale === this._cachedVScale &&
  29639. this.coordinatesMode === this._cachedCoordinatesMode) {
  29640. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  29641. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  29642. return this._cachedTextureMatrix;
  29643. }
  29644. }
  29645. else {
  29646. return this._cachedTextureMatrix;
  29647. }
  29648. }
  29649. if (!this._cachedTextureMatrix) {
  29650. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  29651. }
  29652. if (!this._projectionModeMatrix) {
  29653. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  29654. }
  29655. this._cachedUOffset = this.uOffset;
  29656. this._cachedVOffset = this.vOffset;
  29657. this._cachedUScale = this.uScale;
  29658. this._cachedVScale = this.vScale;
  29659. this._cachedCoordinatesMode = this.coordinatesMode;
  29660. switch (this.coordinatesMode) {
  29661. case Texture.PLANAR_MODE:
  29662. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  29663. this._cachedTextureMatrix[0] = this.uScale;
  29664. this._cachedTextureMatrix[5] = this.vScale;
  29665. this._cachedTextureMatrix[12] = this.uOffset;
  29666. this._cachedTextureMatrix[13] = this.vOffset;
  29667. break;
  29668. case Texture.PROJECTION_MODE:
  29669. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  29670. this._projectionModeMatrix.m[0] = 0.5;
  29671. this._projectionModeMatrix.m[5] = -0.5;
  29672. this._projectionModeMatrix.m[10] = 0.0;
  29673. this._projectionModeMatrix.m[12] = 0.5;
  29674. this._projectionModeMatrix.m[13] = 0.5;
  29675. this._projectionModeMatrix.m[14] = 1.0;
  29676. this._projectionModeMatrix.m[15] = 1.0;
  29677. var projectionMatrix = scene.getProjectionMatrix();
  29678. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  29679. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  29680. break;
  29681. default:
  29682. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  29683. break;
  29684. }
  29685. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  29686. return (mat.getActiveTextures().indexOf(_this) !== -1);
  29687. });
  29688. return this._cachedTextureMatrix;
  29689. };
  29690. Texture.prototype.clone = function () {
  29691. var _this = this;
  29692. return BABYLON.SerializationHelper.Clone(function () {
  29693. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  29694. }, this);
  29695. };
  29696. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  29697. get: function () {
  29698. if (!this._onLoadObservable) {
  29699. this._onLoadObservable = new BABYLON.Observable();
  29700. }
  29701. return this._onLoadObservable;
  29702. },
  29703. enumerable: true,
  29704. configurable: true
  29705. });
  29706. Texture.prototype.serialize = function () {
  29707. var serializationObject = _super.prototype.serialize.call(this);
  29708. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  29709. serializationObject.base64String = this._buffer;
  29710. serializationObject.name = serializationObject.name.replace("data:", "");
  29711. }
  29712. return serializationObject;
  29713. };
  29714. Texture.prototype.getClassName = function () {
  29715. return "Texture";
  29716. };
  29717. Texture.prototype.dispose = function () {
  29718. _super.prototype.dispose.call(this);
  29719. if (this.onLoadObservable) {
  29720. this.onLoadObservable.clear();
  29721. this._onLoadObservable = null;
  29722. }
  29723. this._delayedOnLoad = null;
  29724. this._delayedOnError = null;
  29725. };
  29726. // Statics
  29727. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  29728. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  29729. if (onLoad === void 0) { onLoad = null; }
  29730. if (onError === void 0) { onError = null; }
  29731. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  29732. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  29733. };
  29734. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  29735. if (parsedTexture.customType) {
  29736. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  29737. // Update Sampling Mode
  29738. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  29739. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  29740. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  29741. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  29742. }
  29743. }
  29744. return parsedCustomTexture;
  29745. }
  29746. if (parsedTexture.isCube) {
  29747. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  29748. }
  29749. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  29750. return null;
  29751. }
  29752. var texture = BABYLON.SerializationHelper.Parse(function () {
  29753. var generateMipMaps = true;
  29754. if (parsedTexture.noMipmap) {
  29755. generateMipMaps = false;
  29756. }
  29757. if (parsedTexture.mirrorPlane) {
  29758. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  29759. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  29760. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  29761. return mirrorTexture;
  29762. }
  29763. else if (parsedTexture.isRenderTarget) {
  29764. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  29765. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  29766. return renderTargetTexture;
  29767. }
  29768. else {
  29769. var texture;
  29770. if (parsedTexture.base64String) {
  29771. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  29772. }
  29773. else {
  29774. var url = rootUrl + parsedTexture.name;
  29775. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  29776. url = parsedTexture.url;
  29777. }
  29778. texture = new Texture(url, scene, !generateMipMaps);
  29779. }
  29780. return texture;
  29781. }
  29782. }, parsedTexture, scene);
  29783. // Update Sampling Mode
  29784. if (parsedTexture.samplingMode) {
  29785. var sampling = parsedTexture.samplingMode;
  29786. if (texture._samplingMode !== sampling) {
  29787. texture.updateSamplingMode(sampling);
  29788. }
  29789. }
  29790. // Animations
  29791. if (parsedTexture.animations) {
  29792. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  29793. var parsedAnimation = parsedTexture.animations[animationIndex];
  29794. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29795. }
  29796. }
  29797. return texture;
  29798. };
  29799. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  29800. if (deleteBuffer === void 0) { deleteBuffer = false; }
  29801. if (noMipmap === void 0) { noMipmap = false; }
  29802. if (invertY === void 0) { invertY = true; }
  29803. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  29804. if (onLoad === void 0) { onLoad = null; }
  29805. if (onError === void 0) { onError = null; }
  29806. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  29807. if (name.substr(0, 5) !== "data:") {
  29808. name = "data:" + name;
  29809. }
  29810. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  29811. };
  29812. // Constants
  29813. Texture.NEAREST_SAMPLINGMODE = 1;
  29814. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  29815. Texture.BILINEAR_SAMPLINGMODE = 2;
  29816. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  29817. Texture.TRILINEAR_SAMPLINGMODE = 3;
  29818. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  29819. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  29820. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  29821. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  29822. Texture.NEAREST_LINEAR = 7;
  29823. Texture.NEAREST_NEAREST = 8;
  29824. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  29825. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  29826. Texture.LINEAR_LINEAR = 11;
  29827. Texture.LINEAR_NEAREST = 12;
  29828. Texture.EXPLICIT_MODE = 0;
  29829. Texture.SPHERICAL_MODE = 1;
  29830. Texture.PLANAR_MODE = 2;
  29831. Texture.CUBIC_MODE = 3;
  29832. Texture.PROJECTION_MODE = 4;
  29833. Texture.SKYBOX_MODE = 5;
  29834. Texture.INVCUBIC_MODE = 6;
  29835. Texture.EQUIRECTANGULAR_MODE = 7;
  29836. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  29837. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  29838. Texture.CLAMP_ADDRESSMODE = 0;
  29839. Texture.WRAP_ADDRESSMODE = 1;
  29840. Texture.MIRROR_ADDRESSMODE = 2;
  29841. /**
  29842. * 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
  29843. */
  29844. Texture.UseSerializedUrlIfAny = false;
  29845. __decorate([
  29846. BABYLON.serialize()
  29847. ], Texture.prototype, "url", void 0);
  29848. __decorate([
  29849. BABYLON.serialize()
  29850. ], Texture.prototype, "uOffset", void 0);
  29851. __decorate([
  29852. BABYLON.serialize()
  29853. ], Texture.prototype, "vOffset", void 0);
  29854. __decorate([
  29855. BABYLON.serialize()
  29856. ], Texture.prototype, "uScale", void 0);
  29857. __decorate([
  29858. BABYLON.serialize()
  29859. ], Texture.prototype, "vScale", void 0);
  29860. __decorate([
  29861. BABYLON.serialize()
  29862. ], Texture.prototype, "uAng", void 0);
  29863. __decorate([
  29864. BABYLON.serialize()
  29865. ], Texture.prototype, "vAng", void 0);
  29866. __decorate([
  29867. BABYLON.serialize()
  29868. ], Texture.prototype, "wAng", void 0);
  29869. __decorate([
  29870. BABYLON.serialize()
  29871. ], Texture.prototype, "isBlocking", null);
  29872. return Texture;
  29873. }(BABYLON.BaseTexture));
  29874. BABYLON.Texture = Texture;
  29875. })(BABYLON || (BABYLON = {}));
  29876. //# sourceMappingURL=babylon.texture.js.map
  29877. "use strict";
  29878. var BABYLON;
  29879. (function (BABYLON) {
  29880. var _InstancesBatch = /** @class */ (function () {
  29881. function _InstancesBatch() {
  29882. this.mustReturn = false;
  29883. this.visibleInstances = new Array();
  29884. this.renderSelf = new Array();
  29885. }
  29886. return _InstancesBatch;
  29887. }());
  29888. BABYLON._InstancesBatch = _InstancesBatch;
  29889. var Mesh = /** @class */ (function (_super) {
  29890. __extends(Mesh, _super);
  29891. /**
  29892. * @constructor
  29893. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  29894. * @param {Scene} scene The scene to add this mesh to.
  29895. * @param {Node} parent The parent of this mesh, if it has one
  29896. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  29897. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  29898. * When false, achieved by calling a clone(), also passing False.
  29899. * This will make creation of children, recursive.
  29900. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  29901. */
  29902. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  29903. if (scene === void 0) { scene = null; }
  29904. if (parent === void 0) { parent = null; }
  29905. if (source === void 0) { source = null; }
  29906. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  29907. var _this = _super.call(this, name, scene) || this;
  29908. // Events
  29909. /**
  29910. * An event triggered before rendering the mesh
  29911. */
  29912. _this.onBeforeRenderObservable = new BABYLON.Observable();
  29913. /**
  29914. * An event triggered after rendering the mesh
  29915. */
  29916. _this.onAfterRenderObservable = new BABYLON.Observable();
  29917. /**
  29918. * An event triggered before drawing the mesh
  29919. */
  29920. _this.onBeforeDrawObservable = new BABYLON.Observable();
  29921. // Members
  29922. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29923. _this.instances = new Array();
  29924. _this._LODLevels = new Array();
  29925. _this._visibleInstances = {};
  29926. _this._renderIdForInstances = new Array();
  29927. _this._batchCache = new _InstancesBatch();
  29928. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  29929. // Use by builder only to know what orientation were the mesh build in.
  29930. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  29931. _this.overrideMaterialSideOrientation = null;
  29932. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  29933. // Will be used to save a source mesh reference, If any
  29934. _this._source = null;
  29935. scene = _this.getScene();
  29936. if (source) {
  29937. // Source mesh
  29938. _this._source = source;
  29939. // Geometry
  29940. if (source._geometry) {
  29941. source._geometry.applyToMesh(_this);
  29942. }
  29943. // Deep copy
  29944. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  29945. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix", "_source"]);
  29946. // Metadata
  29947. if (source.metadata && source.metadata.clone) {
  29948. _this.metadata = source.metadata.clone();
  29949. }
  29950. else {
  29951. _this.metadata = source.metadata;
  29952. }
  29953. // Tags
  29954. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  29955. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  29956. }
  29957. // Parent
  29958. _this.parent = source.parent;
  29959. // Pivot
  29960. _this.setPivotMatrix(source.getPivotMatrix());
  29961. _this.id = name + "." + source.id;
  29962. // Material
  29963. _this.material = source.material;
  29964. var index;
  29965. if (!doNotCloneChildren) {
  29966. // Children
  29967. var directDescendants = source.getDescendants(true);
  29968. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  29969. var child = directDescendants[index_1];
  29970. if (child.clone) {
  29971. child.clone(name + "." + child.name, _this);
  29972. }
  29973. }
  29974. }
  29975. // Physics clone
  29976. var physicsEngine = _this.getScene().getPhysicsEngine();
  29977. if (clonePhysicsImpostor && physicsEngine) {
  29978. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  29979. if (impostor) {
  29980. _this.physicsImpostor = impostor.clone(_this);
  29981. }
  29982. }
  29983. // Particles
  29984. for (index = 0; index < scene.particleSystems.length; index++) {
  29985. var system = scene.particleSystems[index];
  29986. if (system.emitter === source) {
  29987. system.clone(system.name, _this);
  29988. }
  29989. }
  29990. _this.computeWorldMatrix(true);
  29991. }
  29992. // Parent
  29993. if (parent !== null) {
  29994. _this.parent = parent;
  29995. }
  29996. return _this;
  29997. }
  29998. Object.defineProperty(Mesh, "FRONTSIDE", {
  29999. /**
  30000. * Mesh side orientation : usually the external or front surface
  30001. */
  30002. get: function () {
  30003. return Mesh._FRONTSIDE;
  30004. },
  30005. enumerable: true,
  30006. configurable: true
  30007. });
  30008. Object.defineProperty(Mesh, "BACKSIDE", {
  30009. /**
  30010. * Mesh side orientation : usually the internal or back surface
  30011. */
  30012. get: function () {
  30013. return Mesh._BACKSIDE;
  30014. },
  30015. enumerable: true,
  30016. configurable: true
  30017. });
  30018. Object.defineProperty(Mesh, "DOUBLESIDE", {
  30019. /**
  30020. * Mesh side orientation : both internal and external or front and back surfaces
  30021. */
  30022. get: function () {
  30023. return Mesh._DOUBLESIDE;
  30024. },
  30025. enumerable: true,
  30026. configurable: true
  30027. });
  30028. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  30029. /**
  30030. * Mesh side orientation : by default, `FRONTSIDE`
  30031. */
  30032. get: function () {
  30033. return Mesh._DEFAULTSIDE;
  30034. },
  30035. enumerable: true,
  30036. configurable: true
  30037. });
  30038. Object.defineProperty(Mesh, "NO_CAP", {
  30039. /**
  30040. * Mesh cap setting : no cap
  30041. */
  30042. get: function () {
  30043. return Mesh._NO_CAP;
  30044. },
  30045. enumerable: true,
  30046. configurable: true
  30047. });
  30048. Object.defineProperty(Mesh, "CAP_START", {
  30049. /**
  30050. * Mesh cap setting : one cap at the beginning of the mesh
  30051. */
  30052. get: function () {
  30053. return Mesh._CAP_START;
  30054. },
  30055. enumerable: true,
  30056. configurable: true
  30057. });
  30058. Object.defineProperty(Mesh, "CAP_END", {
  30059. /**
  30060. * Mesh cap setting : one cap at the end of the mesh
  30061. */
  30062. get: function () {
  30063. return Mesh._CAP_END;
  30064. },
  30065. enumerable: true,
  30066. configurable: true
  30067. });
  30068. Object.defineProperty(Mesh, "CAP_ALL", {
  30069. /**
  30070. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  30071. */
  30072. get: function () {
  30073. return Mesh._CAP_ALL;
  30074. },
  30075. enumerable: true,
  30076. configurable: true
  30077. });
  30078. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  30079. set: function (callback) {
  30080. if (this._onBeforeDrawObserver) {
  30081. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  30082. }
  30083. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  30084. },
  30085. enumerable: true,
  30086. configurable: true
  30087. });
  30088. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  30089. get: function () {
  30090. return this._morphTargetManager;
  30091. },
  30092. set: function (value) {
  30093. if (this._morphTargetManager === value) {
  30094. return;
  30095. }
  30096. this._morphTargetManager = value;
  30097. this._syncGeometryWithMorphTargetManager();
  30098. },
  30099. enumerable: true,
  30100. configurable: true
  30101. });
  30102. Object.defineProperty(Mesh.prototype, "source", {
  30103. get: function () {
  30104. return this._source;
  30105. },
  30106. enumerable: true,
  30107. configurable: true
  30108. });
  30109. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  30110. get: function () {
  30111. return this._unIndexed;
  30112. },
  30113. set: function (value) {
  30114. if (this._unIndexed !== value) {
  30115. this._unIndexed = value;
  30116. this._markSubMeshesAsAttributesDirty();
  30117. }
  30118. },
  30119. enumerable: true,
  30120. configurable: true
  30121. });
  30122. // Methods
  30123. /**
  30124. * Returns the string "Mesh".
  30125. */
  30126. Mesh.prototype.getClassName = function () {
  30127. return "Mesh";
  30128. };
  30129. /**
  30130. * Returns a string.
  30131. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  30132. */
  30133. Mesh.prototype.toString = function (fullDetails) {
  30134. var ret = _super.prototype.toString.call(this, fullDetails);
  30135. ret += ", n vertices: " + this.getTotalVertices();
  30136. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  30137. if (this.animations) {
  30138. for (var i = 0; i < this.animations.length; i++) {
  30139. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  30140. }
  30141. }
  30142. if (fullDetails) {
  30143. if (this._geometry) {
  30144. var ib = this.getIndices();
  30145. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30146. if (vb && ib) {
  30147. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  30148. }
  30149. }
  30150. else {
  30151. ret += ", flat shading: UNKNOWN";
  30152. }
  30153. }
  30154. return ret;
  30155. };
  30156. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  30157. /**
  30158. * True if the mesh has some Levels Of Details (LOD).
  30159. * Returns a boolean.
  30160. */
  30161. get: function () {
  30162. return this._LODLevels.length > 0;
  30163. },
  30164. enumerable: true,
  30165. configurable: true
  30166. });
  30167. /**
  30168. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  30169. * @returns an array of {BABYLON.MeshLODLevel}
  30170. */
  30171. Mesh.prototype.getLODLevels = function () {
  30172. return this._LODLevels;
  30173. };
  30174. Mesh.prototype._sortLODLevels = function () {
  30175. this._LODLevels.sort(function (a, b) {
  30176. if (a.distance < b.distance) {
  30177. return 1;
  30178. }
  30179. if (a.distance > b.distance) {
  30180. return -1;
  30181. }
  30182. return 0;
  30183. });
  30184. };
  30185. /**
  30186. * Add a mesh as LOD level triggered at the given distance.
  30187. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30188. * @param {number} distance The distance from the center of the object to show this level
  30189. * @param {Mesh} mesh The mesh to be added as LOD level
  30190. * @return {Mesh} This mesh (for chaining)
  30191. */
  30192. Mesh.prototype.addLODLevel = function (distance, mesh) {
  30193. if (mesh && mesh._masterMesh) {
  30194. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  30195. return this;
  30196. }
  30197. var level = new BABYLON.MeshLODLevel(distance, mesh);
  30198. this._LODLevels.push(level);
  30199. if (mesh) {
  30200. mesh._masterMesh = this;
  30201. }
  30202. this._sortLODLevels();
  30203. return this;
  30204. };
  30205. /**
  30206. * Returns the LOD level mesh at the passed distance or null if not found.
  30207. * It is related to the method `addLODLevel(distance, mesh)`.
  30208. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30209. * Returns an object Mesh or `null`.
  30210. */
  30211. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  30212. for (var index = 0; index < this._LODLevels.length; index++) {
  30213. var level = this._LODLevels[index];
  30214. if (level.distance === distance) {
  30215. return level.mesh;
  30216. }
  30217. }
  30218. return null;
  30219. };
  30220. /**
  30221. * Remove a mesh from the LOD array
  30222. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30223. * @param {Mesh} mesh The mesh to be removed.
  30224. * @return {Mesh} This mesh (for chaining)
  30225. */
  30226. Mesh.prototype.removeLODLevel = function (mesh) {
  30227. for (var index = 0; index < this._LODLevels.length; index++) {
  30228. if (this._LODLevels[index].mesh === mesh) {
  30229. this._LODLevels.splice(index, 1);
  30230. if (mesh) {
  30231. mesh._masterMesh = null;
  30232. }
  30233. }
  30234. }
  30235. this._sortLODLevels();
  30236. return this;
  30237. };
  30238. /**
  30239. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  30240. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30241. */
  30242. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  30243. if (!this._LODLevels || this._LODLevels.length === 0) {
  30244. return this;
  30245. }
  30246. var bSphere;
  30247. if (boundingSphere) {
  30248. bSphere = boundingSphere;
  30249. }
  30250. else {
  30251. var boundingInfo = this.getBoundingInfo();
  30252. bSphere = boundingInfo.boundingSphere;
  30253. }
  30254. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  30255. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  30256. if (this.onLODLevelSelection) {
  30257. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  30258. }
  30259. return this;
  30260. }
  30261. for (var index = 0; index < this._LODLevels.length; index++) {
  30262. var level = this._LODLevels[index];
  30263. if (level.distance < distanceToCamera) {
  30264. if (level.mesh) {
  30265. level.mesh._preActivate();
  30266. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  30267. }
  30268. if (this.onLODLevelSelection) {
  30269. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  30270. }
  30271. return level.mesh;
  30272. }
  30273. }
  30274. if (this.onLODLevelSelection) {
  30275. this.onLODLevelSelection(distanceToCamera, this, this);
  30276. }
  30277. return this;
  30278. };
  30279. Object.defineProperty(Mesh.prototype, "geometry", {
  30280. /**
  30281. * Returns the mesh internal Geometry object.
  30282. */
  30283. get: function () {
  30284. return this._geometry;
  30285. },
  30286. enumerable: true,
  30287. configurable: true
  30288. });
  30289. /**
  30290. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  30291. */
  30292. Mesh.prototype.getTotalVertices = function () {
  30293. if (this._geometry === null || this._geometry === undefined) {
  30294. return 0;
  30295. }
  30296. return this._geometry.getTotalVertices();
  30297. };
  30298. /**
  30299. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  30300. * 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.
  30301. * You can force the copy with forceCopy === true
  30302. * Returns null if the mesh has no geometry or no vertex buffer.
  30303. * Possible `kind` values :
  30304. * - BABYLON.VertexBuffer.PositionKind
  30305. * - BABYLON.VertexBuffer.UVKind
  30306. * - BABYLON.VertexBuffer.UV2Kind
  30307. * - BABYLON.VertexBuffer.UV3Kind
  30308. * - BABYLON.VertexBuffer.UV4Kind
  30309. * - BABYLON.VertexBuffer.UV5Kind
  30310. * - BABYLON.VertexBuffer.UV6Kind
  30311. * - BABYLON.VertexBuffer.ColorKind
  30312. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30313. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30314. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30315. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30316. */
  30317. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  30318. if (!this._geometry) {
  30319. return null;
  30320. }
  30321. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  30322. };
  30323. /**
  30324. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  30325. * Returns `null` if the mesh has no geometry.
  30326. * Possible `kind` values :
  30327. * - BABYLON.VertexBuffer.PositionKind
  30328. * - BABYLON.VertexBuffer.UVKind
  30329. * - BABYLON.VertexBuffer.UV2Kind
  30330. * - BABYLON.VertexBuffer.UV3Kind
  30331. * - BABYLON.VertexBuffer.UV4Kind
  30332. * - BABYLON.VertexBuffer.UV5Kind
  30333. * - BABYLON.VertexBuffer.UV6Kind
  30334. * - BABYLON.VertexBuffer.ColorKind
  30335. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30336. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30337. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30338. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30339. */
  30340. Mesh.prototype.getVertexBuffer = function (kind) {
  30341. if (!this._geometry) {
  30342. return null;
  30343. }
  30344. return this._geometry.getVertexBuffer(kind);
  30345. };
  30346. /**
  30347. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  30348. * Possible `kind` values :
  30349. * - BABYLON.VertexBuffer.PositionKind
  30350. * - BABYLON.VertexBuffer.UVKind
  30351. * - BABYLON.VertexBuffer.UV2Kind
  30352. * - BABYLON.VertexBuffer.UV3Kind
  30353. * - BABYLON.VertexBuffer.UV4Kind
  30354. * - BABYLON.VertexBuffer.UV5Kind
  30355. * - BABYLON.VertexBuffer.UV6Kind
  30356. * - BABYLON.VertexBuffer.ColorKind
  30357. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30358. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30359. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30360. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30361. */
  30362. Mesh.prototype.isVerticesDataPresent = function (kind) {
  30363. if (!this._geometry) {
  30364. if (this._delayInfo) {
  30365. return this._delayInfo.indexOf(kind) !== -1;
  30366. }
  30367. return false;
  30368. }
  30369. return this._geometry.isVerticesDataPresent(kind);
  30370. };
  30371. /**
  30372. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  30373. * Possible `kind` values :
  30374. * - BABYLON.VertexBuffer.PositionKind
  30375. * - BABYLON.VertexBuffer.UVKind
  30376. * - BABYLON.VertexBuffer.UV2Kind
  30377. * - BABYLON.VertexBuffer.UV3Kind
  30378. * - BABYLON.VertexBuffer.UV4Kind
  30379. * - BABYLON.VertexBuffer.UV5Kind
  30380. * - BABYLON.VertexBuffer.UV6Kind
  30381. * - BABYLON.VertexBuffer.ColorKind
  30382. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30383. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30384. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30385. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30386. */
  30387. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  30388. if (!this._geometry) {
  30389. if (this._delayInfo) {
  30390. return this._delayInfo.indexOf(kind) !== -1;
  30391. }
  30392. return false;
  30393. }
  30394. return this._geometry.isVertexBufferUpdatable(kind);
  30395. };
  30396. /**
  30397. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  30398. * Possible `kind` values :
  30399. * - BABYLON.VertexBuffer.PositionKind
  30400. * - BABYLON.VertexBuffer.UVKind
  30401. * - BABYLON.VertexBuffer.UV2Kind
  30402. * - BABYLON.VertexBuffer.UV3Kind
  30403. * - BABYLON.VertexBuffer.UV4Kind
  30404. * - BABYLON.VertexBuffer.UV5Kind
  30405. * - BABYLON.VertexBuffer.UV6Kind
  30406. * - BABYLON.VertexBuffer.ColorKind
  30407. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30408. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30409. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30410. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30411. */
  30412. Mesh.prototype.getVerticesDataKinds = function () {
  30413. if (!this._geometry) {
  30414. var result = new Array();
  30415. if (this._delayInfo) {
  30416. this._delayInfo.forEach(function (kind, index, array) {
  30417. result.push(kind);
  30418. });
  30419. }
  30420. return result;
  30421. }
  30422. return this._geometry.getVerticesDataKinds();
  30423. };
  30424. /**
  30425. * Returns a positive integer : the total number of indices in this mesh geometry.
  30426. * Returns zero if the mesh has no geometry.
  30427. */
  30428. Mesh.prototype.getTotalIndices = function () {
  30429. if (!this._geometry) {
  30430. return 0;
  30431. }
  30432. return this._geometry.getTotalIndices();
  30433. };
  30434. /**
  30435. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  30436. * 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.
  30437. * Returns an empty array if the mesh has no geometry.
  30438. */
  30439. Mesh.prototype.getIndices = function (copyWhenShared) {
  30440. if (!this._geometry) {
  30441. return [];
  30442. }
  30443. return this._geometry.getIndices(copyWhenShared);
  30444. };
  30445. Object.defineProperty(Mesh.prototype, "isBlocked", {
  30446. get: function () {
  30447. return this._masterMesh !== null && this._masterMesh !== undefined;
  30448. },
  30449. enumerable: true,
  30450. configurable: true
  30451. });
  30452. /**
  30453. * Determine if the current mesh is ready to be rendered
  30454. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  30455. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  30456. * @returns true if all associated assets are ready (material, textures, shaders)
  30457. */
  30458. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  30459. if (completeCheck === void 0) { completeCheck = false; }
  30460. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  30461. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  30462. return false;
  30463. }
  30464. if (!_super.prototype.isReady.call(this, completeCheck)) {
  30465. return false;
  30466. }
  30467. if (!this.subMeshes || this.subMeshes.length === 0) {
  30468. return true;
  30469. }
  30470. if (!completeCheck) {
  30471. return true;
  30472. }
  30473. var engine = this.getEngine();
  30474. var scene = this.getScene();
  30475. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  30476. this.computeWorldMatrix();
  30477. var mat = this.material || scene.defaultMaterial;
  30478. if (mat) {
  30479. if (mat.storeEffectOnSubMeshes) {
  30480. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  30481. var subMesh = _a[_i];
  30482. var effectiveMaterial = subMesh.getMaterial();
  30483. if (effectiveMaterial) {
  30484. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  30485. return false;
  30486. }
  30487. }
  30488. }
  30489. }
  30490. else {
  30491. if (!mat.isReady(this, hardwareInstancedRendering)) {
  30492. return false;
  30493. }
  30494. }
  30495. }
  30496. // Shadows
  30497. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  30498. var light = _c[_b];
  30499. var generator = light.getShadowGenerator();
  30500. if (generator) {
  30501. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  30502. var subMesh = _e[_d];
  30503. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  30504. return false;
  30505. }
  30506. }
  30507. }
  30508. }
  30509. // LOD
  30510. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  30511. var lod = _g[_f];
  30512. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  30513. return false;
  30514. }
  30515. }
  30516. return true;
  30517. };
  30518. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  30519. /**
  30520. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  30521. * This property is pertinent only for updatable parametric shapes.
  30522. */
  30523. get: function () {
  30524. return this._areNormalsFrozen;
  30525. },
  30526. enumerable: true,
  30527. configurable: true
  30528. });
  30529. /**
  30530. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  30531. * It has no effect at all on other shapes.
  30532. * It prevents the mesh normals from being recomputed on next `positions` array update.
  30533. * Returns the Mesh.
  30534. */
  30535. Mesh.prototype.freezeNormals = function () {
  30536. this._areNormalsFrozen = true;
  30537. return this;
  30538. };
  30539. /**
  30540. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  30541. * It has no effect at all on other shapes.
  30542. * It reactivates the mesh normals computation if it was previously frozen.
  30543. * Returns the Mesh.
  30544. */
  30545. Mesh.prototype.unfreezeNormals = function () {
  30546. this._areNormalsFrozen = false;
  30547. return this;
  30548. };
  30549. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  30550. /**
  30551. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  30552. */
  30553. set: function (count) {
  30554. this._overridenInstanceCount = count;
  30555. },
  30556. enumerable: true,
  30557. configurable: true
  30558. });
  30559. // Methods
  30560. Mesh.prototype._preActivate = function () {
  30561. var sceneRenderId = this.getScene().getRenderId();
  30562. if (this._preActivateId === sceneRenderId) {
  30563. return this;
  30564. }
  30565. this._preActivateId = sceneRenderId;
  30566. this._visibleInstances = null;
  30567. return this;
  30568. };
  30569. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  30570. if (this._visibleInstances) {
  30571. this._visibleInstances.intermediateDefaultRenderId = renderId;
  30572. }
  30573. return this;
  30574. };
  30575. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  30576. if (!this._visibleInstances) {
  30577. this._visibleInstances = {};
  30578. this._visibleInstances.defaultRenderId = renderId;
  30579. this._visibleInstances.selfDefaultRenderId = this._renderId;
  30580. }
  30581. if (!this._visibleInstances[renderId]) {
  30582. this._visibleInstances[renderId] = new Array();
  30583. }
  30584. this._visibleInstances[renderId].push(instance);
  30585. return this;
  30586. };
  30587. /**
  30588. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  30589. * This means the mesh underlying bounding box and sphere are recomputed.
  30590. * Returns the Mesh.
  30591. */
  30592. Mesh.prototype.refreshBoundingInfo = function () {
  30593. return this._refreshBoundingInfo(false);
  30594. };
  30595. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  30596. if (this._boundingInfo && this._boundingInfo.isLocked) {
  30597. return this;
  30598. }
  30599. var data = this._getPositionData(applySkeleton);
  30600. if (data) {
  30601. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  30602. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  30603. }
  30604. if (this.subMeshes) {
  30605. for (var index = 0; index < this.subMeshes.length; index++) {
  30606. this.subMeshes[index].refreshBoundingInfo();
  30607. }
  30608. }
  30609. this._updateBoundingInfo();
  30610. return this;
  30611. };
  30612. Mesh.prototype._getPositionData = function (applySkeleton) {
  30613. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30614. if (data && applySkeleton && this.skeleton) {
  30615. data = BABYLON.Tools.Slice(data);
  30616. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30617. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  30618. if (matricesWeightsData && matricesIndicesData) {
  30619. var needExtras = this.numBoneInfluencers > 4;
  30620. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  30621. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  30622. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  30623. var tempVector = BABYLON.Tmp.Vector3[0];
  30624. var finalMatrix = BABYLON.Tmp.Matrix[0];
  30625. var tempMatrix = BABYLON.Tmp.Matrix[1];
  30626. var matWeightIdx = 0;
  30627. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  30628. finalMatrix.reset();
  30629. var inf;
  30630. var weight;
  30631. for (inf = 0; inf < 4; inf++) {
  30632. weight = matricesWeightsData[matWeightIdx + inf];
  30633. if (weight <= 0)
  30634. break;
  30635. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30636. finalMatrix.addToSelf(tempMatrix);
  30637. }
  30638. if (needExtras) {
  30639. for (inf = 0; inf < 4; inf++) {
  30640. weight = matricesWeightsExtraData[matWeightIdx + inf];
  30641. if (weight <= 0)
  30642. break;
  30643. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30644. finalMatrix.addToSelf(tempMatrix);
  30645. }
  30646. }
  30647. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  30648. tempVector.toArray(data, index);
  30649. }
  30650. }
  30651. }
  30652. return data;
  30653. };
  30654. Mesh.prototype._createGlobalSubMesh = function (force) {
  30655. var totalVertices = this.getTotalVertices();
  30656. if (!totalVertices || !this.getIndices()) {
  30657. return null;
  30658. }
  30659. // Check if we need to recreate the submeshes
  30660. if (this.subMeshes && this.subMeshes.length > 0) {
  30661. var ib = this.getIndices();
  30662. if (!ib) {
  30663. return null;
  30664. }
  30665. var totalIndices = ib.length;
  30666. var needToRecreate = false;
  30667. if (force) {
  30668. needToRecreate = true;
  30669. }
  30670. else {
  30671. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  30672. var submesh = _a[_i];
  30673. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  30674. needToRecreate = true;
  30675. break;
  30676. }
  30677. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  30678. needToRecreate = true;
  30679. break;
  30680. }
  30681. }
  30682. }
  30683. if (!needToRecreate) {
  30684. return this.subMeshes[0];
  30685. }
  30686. }
  30687. this.releaseSubMeshes();
  30688. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  30689. };
  30690. Mesh.prototype.subdivide = function (count) {
  30691. if (count < 1) {
  30692. return;
  30693. }
  30694. var totalIndices = this.getTotalIndices();
  30695. var subdivisionSize = (totalIndices / count) | 0;
  30696. var offset = 0;
  30697. // Ensure that subdivisionSize is a multiple of 3
  30698. while (subdivisionSize % 3 !== 0) {
  30699. subdivisionSize++;
  30700. }
  30701. this.releaseSubMeshes();
  30702. for (var index = 0; index < count; index++) {
  30703. if (offset >= totalIndices) {
  30704. break;
  30705. }
  30706. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  30707. offset += subdivisionSize;
  30708. }
  30709. this.synchronizeInstances();
  30710. };
  30711. /**
  30712. * Sets the vertex data of the mesh geometry for the requested `kind`.
  30713. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  30714. * The `data` are either a numeric array either a Float32Array.
  30715. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  30716. * 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).
  30717. * Note that a new underlying VertexBuffer object is created each call.
  30718. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  30719. *
  30720. * Possible `kind` values :
  30721. * - BABYLON.VertexBuffer.PositionKind
  30722. * - BABYLON.VertexBuffer.UVKind
  30723. * - BABYLON.VertexBuffer.UV2Kind
  30724. * - BABYLON.VertexBuffer.UV3Kind
  30725. * - BABYLON.VertexBuffer.UV4Kind
  30726. * - BABYLON.VertexBuffer.UV5Kind
  30727. * - BABYLON.VertexBuffer.UV6Kind
  30728. * - BABYLON.VertexBuffer.ColorKind
  30729. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30730. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30731. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30732. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30733. *
  30734. * Returns the Mesh.
  30735. */
  30736. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  30737. if (updatable === void 0) { updatable = false; }
  30738. if (!this._geometry) {
  30739. var vertexData = new BABYLON.VertexData();
  30740. vertexData.set(data, kind);
  30741. var scene = this.getScene();
  30742. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  30743. }
  30744. else {
  30745. this._geometry.setVerticesData(kind, data, updatable, stride);
  30746. }
  30747. return this;
  30748. };
  30749. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  30750. if (updatable === void 0) { updatable = true; }
  30751. var vb = this.getVertexBuffer(kind);
  30752. if (!vb || vb.isUpdatable() === updatable) {
  30753. return;
  30754. }
  30755. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  30756. };
  30757. /**
  30758. * Sets the mesh VertexBuffer.
  30759. * Returns the Mesh.
  30760. */
  30761. Mesh.prototype.setVerticesBuffer = function (buffer) {
  30762. if (!this._geometry) {
  30763. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  30764. }
  30765. this._geometry.setVerticesBuffer(buffer);
  30766. return this;
  30767. };
  30768. /**
  30769. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  30770. * If the mesh has no geometry, it is simply returned as it is.
  30771. * The `data` are either a numeric array either a Float32Array.
  30772. * No new underlying VertexBuffer object is created.
  30773. * 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.
  30774. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  30775. *
  30776. * Possible `kind` values :
  30777. * - BABYLON.VertexBuffer.PositionKind
  30778. * - BABYLON.VertexBuffer.UVKind
  30779. * - BABYLON.VertexBuffer.UV2Kind
  30780. * - BABYLON.VertexBuffer.UV3Kind
  30781. * - BABYLON.VertexBuffer.UV4Kind
  30782. * - BABYLON.VertexBuffer.UV5Kind
  30783. * - BABYLON.VertexBuffer.UV6Kind
  30784. * - BABYLON.VertexBuffer.ColorKind
  30785. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30786. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30787. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30788. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30789. *
  30790. * Returns the Mesh.
  30791. */
  30792. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  30793. if (!this._geometry) {
  30794. return this;
  30795. }
  30796. if (!makeItUnique) {
  30797. this._geometry.updateVerticesData(kind, data, updateExtends);
  30798. }
  30799. else {
  30800. this.makeGeometryUnique();
  30801. this.updateVerticesData(kind, data, updateExtends, false);
  30802. }
  30803. return this;
  30804. };
  30805. /**
  30806. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  30807. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  30808. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  30809. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  30810. * Returns the Mesh.
  30811. */
  30812. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  30813. if (computeNormals === void 0) { computeNormals = true; }
  30814. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30815. if (!positions) {
  30816. return this;
  30817. }
  30818. positionFunction(positions);
  30819. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  30820. if (computeNormals) {
  30821. var indices = this.getIndices();
  30822. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30823. if (!normals) {
  30824. return this;
  30825. }
  30826. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  30827. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  30828. }
  30829. return this;
  30830. };
  30831. /**
  30832. * Creates a un-shared specific occurence of the geometry for the mesh.
  30833. * Returns the Mesh.
  30834. */
  30835. Mesh.prototype.makeGeometryUnique = function () {
  30836. if (!this._geometry) {
  30837. return this;
  30838. }
  30839. var oldGeometry = this._geometry;
  30840. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  30841. oldGeometry.releaseForMesh(this, true);
  30842. geometry.applyToMesh(this);
  30843. return this;
  30844. };
  30845. /**
  30846. * Sets the mesh indices.
  30847. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  30848. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  30849. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  30850. * This method creates a new index buffer each call.
  30851. * Returns the Mesh.
  30852. */
  30853. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  30854. if (totalVertices === void 0) { totalVertices = null; }
  30855. if (updatable === void 0) { updatable = false; }
  30856. if (!this._geometry) {
  30857. var vertexData = new BABYLON.VertexData();
  30858. vertexData.indices = indices;
  30859. var scene = this.getScene();
  30860. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  30861. }
  30862. else {
  30863. this._geometry.setIndices(indices, totalVertices, updatable);
  30864. }
  30865. return this;
  30866. };
  30867. /**
  30868. * Update the current index buffer
  30869. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  30870. * Returns the Mesh.
  30871. */
  30872. Mesh.prototype.updateIndices = function (indices, offset) {
  30873. if (!this._geometry) {
  30874. return this;
  30875. }
  30876. this._geometry.updateIndices(indices, offset);
  30877. return this;
  30878. };
  30879. /**
  30880. * Invert the geometry to move from a right handed system to a left handed one.
  30881. * Returns the Mesh.
  30882. */
  30883. Mesh.prototype.toLeftHanded = function () {
  30884. if (!this._geometry) {
  30885. return this;
  30886. }
  30887. this._geometry.toLeftHanded();
  30888. return this;
  30889. };
  30890. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  30891. if (!this._geometry) {
  30892. return this;
  30893. }
  30894. var engine = this.getScene().getEngine();
  30895. // Wireframe
  30896. var indexToBind;
  30897. if (this._unIndexed) {
  30898. indexToBind = null;
  30899. }
  30900. else {
  30901. switch (fillMode) {
  30902. case BABYLON.Material.PointFillMode:
  30903. indexToBind = null;
  30904. break;
  30905. case BABYLON.Material.WireFrameFillMode:
  30906. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  30907. break;
  30908. default:
  30909. case BABYLON.Material.TriangleFillMode:
  30910. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  30911. break;
  30912. }
  30913. }
  30914. // VBOs
  30915. this._geometry._bind(effect, indexToBind);
  30916. return this;
  30917. };
  30918. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  30919. if (alternate === void 0) { alternate = false; }
  30920. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  30921. return this;
  30922. }
  30923. this.onBeforeDrawObservable.notifyObservers(this);
  30924. var scene = this.getScene();
  30925. var engine = scene.getEngine();
  30926. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  30927. // or triangles as points
  30928. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  30929. }
  30930. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  30931. // Triangles as wireframe
  30932. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  30933. }
  30934. else {
  30935. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  30936. }
  30937. if (scene._isAlternateRenderingEnabled && !alternate) {
  30938. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  30939. if (!effect || !scene.activeCamera) {
  30940. return this;
  30941. }
  30942. scene._switchToAlternateCameraConfiguration(true);
  30943. this._effectiveMaterial.bindView(effect);
  30944. this._effectiveMaterial.bindViewProjection(effect);
  30945. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  30946. this._draw(subMesh, fillMode, instancesCount, true);
  30947. engine.setViewport(scene.activeCamera.viewport);
  30948. scene._switchToAlternateCameraConfiguration(false);
  30949. this._effectiveMaterial.bindView(effect);
  30950. this._effectiveMaterial.bindViewProjection(effect);
  30951. }
  30952. return this;
  30953. };
  30954. /**
  30955. * Registers for this mesh a javascript function called just before the rendering process.
  30956. * This function is passed the current mesh.
  30957. * Return the Mesh.
  30958. */
  30959. Mesh.prototype.registerBeforeRender = function (func) {
  30960. this.onBeforeRenderObservable.add(func);
  30961. return this;
  30962. };
  30963. /**
  30964. * Disposes a previously registered javascript function called before the rendering.
  30965. * This function is passed the current mesh.
  30966. * Returns the Mesh.
  30967. */
  30968. Mesh.prototype.unregisterBeforeRender = function (func) {
  30969. this.onBeforeRenderObservable.removeCallback(func);
  30970. return this;
  30971. };
  30972. /**
  30973. * Registers for this mesh a javascript function called just after the rendering is complete.
  30974. * This function is passed the current mesh.
  30975. * Returns the Mesh.
  30976. */
  30977. Mesh.prototype.registerAfterRender = function (func) {
  30978. this.onAfterRenderObservable.add(func);
  30979. return this;
  30980. };
  30981. /**
  30982. * Disposes a previously registered javascript function called after the rendering.
  30983. * This function is passed the current mesh.
  30984. * Return the Mesh.
  30985. */
  30986. Mesh.prototype.unregisterAfterRender = function (func) {
  30987. this.onAfterRenderObservable.removeCallback(func);
  30988. return this;
  30989. };
  30990. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  30991. var scene = this.getScene();
  30992. this._batchCache.mustReturn = false;
  30993. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  30994. this._batchCache.visibleInstances[subMeshId] = null;
  30995. if (this._visibleInstances) {
  30996. var currentRenderId = scene.getRenderId();
  30997. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  30998. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  30999. var selfRenderId = this._renderId;
  31000. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  31001. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  31002. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  31003. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  31004. }
  31005. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  31006. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  31007. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  31008. this._batchCache.mustReturn = true;
  31009. return this._batchCache;
  31010. }
  31011. if (currentRenderId !== selfRenderId) {
  31012. this._batchCache.renderSelf[subMeshId] = false;
  31013. }
  31014. }
  31015. this._renderIdForInstances[subMeshId] = currentRenderId;
  31016. }
  31017. return this._batchCache;
  31018. };
  31019. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  31020. var visibleInstances = batch.visibleInstances[subMesh._id];
  31021. if (!visibleInstances) {
  31022. return this;
  31023. }
  31024. var matricesCount = visibleInstances.length + 1;
  31025. var bufferSize = matricesCount * 16 * 4;
  31026. var currentInstancesBufferSize = this._instancesBufferSize;
  31027. var instancesBuffer = this._instancesBuffer;
  31028. while (this._instancesBufferSize < bufferSize) {
  31029. this._instancesBufferSize *= 2;
  31030. }
  31031. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  31032. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  31033. }
  31034. var offset = 0;
  31035. var instancesCount = 0;
  31036. var world = this.getWorldMatrix();
  31037. if (batch.renderSelf[subMesh._id]) {
  31038. world.copyToArray(this._instancesData, offset);
  31039. offset += 16;
  31040. instancesCount++;
  31041. }
  31042. if (visibleInstances) {
  31043. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  31044. var instance = visibleInstances[instanceIndex];
  31045. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  31046. offset += 16;
  31047. instancesCount++;
  31048. }
  31049. }
  31050. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  31051. if (instancesBuffer) {
  31052. instancesBuffer.dispose();
  31053. }
  31054. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  31055. this._instancesBuffer = instancesBuffer;
  31056. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  31057. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  31058. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  31059. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  31060. }
  31061. else {
  31062. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  31063. }
  31064. this._bind(subMesh, effect, fillMode);
  31065. this._draw(subMesh, fillMode, instancesCount);
  31066. engine.unbindInstanceAttributes();
  31067. return this;
  31068. };
  31069. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  31070. var scene = this.getScene();
  31071. var engine = scene.getEngine();
  31072. if (hardwareInstancedRendering) {
  31073. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  31074. }
  31075. else {
  31076. if (batch.renderSelf[subMesh._id]) {
  31077. // Draw
  31078. if (onBeforeDraw) {
  31079. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  31080. }
  31081. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  31082. }
  31083. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  31084. if (visibleInstancesForSubMesh) {
  31085. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  31086. var instance = visibleInstancesForSubMesh[instanceIndex];
  31087. // World
  31088. var world = instance.getWorldMatrix();
  31089. if (onBeforeDraw) {
  31090. onBeforeDraw(true, world, effectiveMaterial);
  31091. }
  31092. // Draw
  31093. this._draw(subMesh, fillMode);
  31094. }
  31095. }
  31096. }
  31097. return this;
  31098. };
  31099. /**
  31100. * Triggers the draw call for the mesh.
  31101. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  31102. * Returns the Mesh.
  31103. */
  31104. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  31105. this.checkOcclusionQuery();
  31106. if (this._isOccluded) {
  31107. return this;
  31108. }
  31109. var scene = this.getScene();
  31110. // Managing instances
  31111. var batch = this._getInstancesRenderList(subMesh._id);
  31112. if (batch.mustReturn) {
  31113. return this;
  31114. }
  31115. // Checking geometry state
  31116. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31117. return this;
  31118. }
  31119. this.onBeforeRenderObservable.notifyObservers(this);
  31120. var engine = scene.getEngine();
  31121. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  31122. // Material
  31123. var material = subMesh.getMaterial();
  31124. if (!material) {
  31125. return this;
  31126. }
  31127. this._effectiveMaterial = material;
  31128. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31129. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31130. return this;
  31131. }
  31132. }
  31133. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31134. return this;
  31135. }
  31136. // Alpha mode
  31137. if (enableAlphaMode) {
  31138. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  31139. }
  31140. // Outline - step 1
  31141. var savedDepthWrite = engine.getDepthWrite();
  31142. if (this.renderOutline) {
  31143. engine.setDepthWrite(false);
  31144. scene.getOutlineRenderer().render(subMesh, batch);
  31145. engine.setDepthWrite(savedDepthWrite);
  31146. }
  31147. var effect;
  31148. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31149. effect = subMesh.effect;
  31150. }
  31151. else {
  31152. effect = this._effectiveMaterial.getEffect();
  31153. }
  31154. if (!effect) {
  31155. return this;
  31156. }
  31157. var sideOrientation = this.overrideMaterialSideOrientation;
  31158. if (sideOrientation == null) {
  31159. sideOrientation = this._effectiveMaterial.sideOrientation;
  31160. if (this._getWorldMatrixDeterminant() < 0) {
  31161. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  31162. }
  31163. }
  31164. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  31165. if (this._effectiveMaterial.forceDepthWrite) {
  31166. engine.setDepthWrite(true);
  31167. }
  31168. // Bind
  31169. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  31170. if (!hardwareInstancedRendering) {
  31171. this._bind(subMesh, effect, fillMode);
  31172. }
  31173. var world = this.getWorldMatrix();
  31174. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31175. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  31176. }
  31177. else {
  31178. this._effectiveMaterial.bind(world, this);
  31179. }
  31180. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  31181. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  31182. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  31183. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  31184. }
  31185. // Draw
  31186. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  31187. // Unbind
  31188. this._effectiveMaterial.unbind();
  31189. // Outline - step 2
  31190. if (this.renderOutline && savedDepthWrite) {
  31191. engine.setDepthWrite(true);
  31192. engine.setColorWrite(false);
  31193. scene.getOutlineRenderer().render(subMesh, batch);
  31194. engine.setColorWrite(true);
  31195. }
  31196. // Overlay
  31197. if (this.renderOverlay) {
  31198. var currentMode = engine.getAlphaMode();
  31199. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  31200. scene.getOutlineRenderer().render(subMesh, batch, true);
  31201. engine.setAlphaMode(currentMode);
  31202. }
  31203. this.onAfterRenderObservable.notifyObservers(this);
  31204. return this;
  31205. };
  31206. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  31207. if (isInstance && effectiveMaterial) {
  31208. effectiveMaterial.bindOnlyWorldMatrix(world);
  31209. }
  31210. };
  31211. /**
  31212. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  31213. */
  31214. Mesh.prototype.getEmittedParticleSystems = function () {
  31215. var results = new Array();
  31216. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  31217. var particleSystem = this.getScene().particleSystems[index];
  31218. if (particleSystem.emitter === this) {
  31219. results.push(particleSystem);
  31220. }
  31221. }
  31222. return results;
  31223. };
  31224. /**
  31225. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  31226. */
  31227. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  31228. var results = new Array();
  31229. var descendants = this.getDescendants();
  31230. descendants.push(this);
  31231. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  31232. var particleSystem = this.getScene().particleSystems[index];
  31233. var emitter = particleSystem.emitter;
  31234. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  31235. results.push(particleSystem);
  31236. }
  31237. }
  31238. return results;
  31239. };
  31240. Mesh.prototype._checkDelayState = function () {
  31241. var scene = this.getScene();
  31242. if (this._geometry) {
  31243. this._geometry.load(scene);
  31244. }
  31245. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31246. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  31247. this._queueLoad(scene);
  31248. }
  31249. return this;
  31250. };
  31251. Mesh.prototype._queueLoad = function (scene) {
  31252. var _this = this;
  31253. scene._addPendingData(this);
  31254. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  31255. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  31256. if (data instanceof ArrayBuffer) {
  31257. _this._delayLoadingFunction(data, _this);
  31258. }
  31259. else {
  31260. _this._delayLoadingFunction(JSON.parse(data), _this);
  31261. }
  31262. _this.instances.forEach(function (instance) {
  31263. instance._syncSubMeshes();
  31264. });
  31265. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31266. scene._removePendingData(_this);
  31267. }, function () { }, scene.database, getBinaryData);
  31268. return this;
  31269. };
  31270. /**
  31271. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  31272. */
  31273. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  31274. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31275. return false;
  31276. }
  31277. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  31278. return false;
  31279. }
  31280. this._checkDelayState();
  31281. return true;
  31282. };
  31283. /**
  31284. * Sets the mesh material by the material or multiMaterial `id` property.
  31285. * The material `id` is a string identifying the material or the multiMaterial.
  31286. * This method returns the Mesh.
  31287. */
  31288. Mesh.prototype.setMaterialByID = function (id) {
  31289. var materials = this.getScene().materials;
  31290. var index;
  31291. for (index = materials.length - 1; index > -1; index--) {
  31292. if (materials[index].id === id) {
  31293. this.material = materials[index];
  31294. return this;
  31295. }
  31296. }
  31297. // Multi
  31298. var multiMaterials = this.getScene().multiMaterials;
  31299. for (index = multiMaterials.length - 1; index > -1; index--) {
  31300. if (multiMaterials[index].id === id) {
  31301. this.material = multiMaterials[index];
  31302. return this;
  31303. }
  31304. }
  31305. return this;
  31306. };
  31307. /**
  31308. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  31309. */
  31310. Mesh.prototype.getAnimatables = function () {
  31311. var results = new Array();
  31312. if (this.material) {
  31313. results.push(this.material);
  31314. }
  31315. if (this.skeleton) {
  31316. results.push(this.skeleton);
  31317. }
  31318. return results;
  31319. };
  31320. /**
  31321. * Modifies the mesh geometry according to the passed transformation matrix.
  31322. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  31323. * The mesh normals are modified accordingly the same transformation.
  31324. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  31325. * Note that, under the hood, this method sets a new VertexBuffer each call.
  31326. * Returns the Mesh.
  31327. */
  31328. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  31329. // Position
  31330. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  31331. return this;
  31332. }
  31333. var submeshes = this.subMeshes.splice(0);
  31334. this._resetPointsArrayCache();
  31335. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31336. var temp = new Array();
  31337. var index;
  31338. for (index = 0; index < data.length; index += 3) {
  31339. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  31340. }
  31341. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  31342. // Normals
  31343. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  31344. return this;
  31345. }
  31346. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31347. temp = [];
  31348. for (index = 0; index < data.length; index += 3) {
  31349. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  31350. }
  31351. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  31352. // flip faces?
  31353. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  31354. this.flipFaces();
  31355. }
  31356. // Restore submeshes
  31357. this.releaseSubMeshes();
  31358. this.subMeshes = submeshes;
  31359. return this;
  31360. };
  31361. /**
  31362. * Modifies the mesh geometry according to its own current World Matrix.
  31363. * The mesh World Matrix is then reset.
  31364. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  31365. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  31366. * Note that, under the hood, this method sets a new VertexBuffer each call.
  31367. * Returns the Mesh.
  31368. */
  31369. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  31370. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  31371. this.scaling.copyFromFloats(1, 1, 1);
  31372. this.position.copyFromFloats(0, 0, 0);
  31373. this.rotation.copyFromFloats(0, 0, 0);
  31374. //only if quaternion is already set
  31375. if (this.rotationQuaternion) {
  31376. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  31377. }
  31378. this._worldMatrix = BABYLON.Matrix.Identity();
  31379. return this;
  31380. };
  31381. Object.defineProperty(Mesh.prototype, "_positions", {
  31382. // Cache
  31383. get: function () {
  31384. if (this._geometry) {
  31385. return this._geometry._positions;
  31386. }
  31387. return null;
  31388. },
  31389. enumerable: true,
  31390. configurable: true
  31391. });
  31392. Mesh.prototype._resetPointsArrayCache = function () {
  31393. if (this._geometry) {
  31394. this._geometry._resetPointsArrayCache();
  31395. }
  31396. return this;
  31397. };
  31398. Mesh.prototype._generatePointsArray = function () {
  31399. if (this._geometry) {
  31400. return this._geometry._generatePointsArray();
  31401. }
  31402. return false;
  31403. };
  31404. /**
  31405. * Returns a new Mesh object generated from the current mesh properties.
  31406. * This method must not get confused with createInstance().
  31407. * The parameter `name` is a string, the name given to the new mesh.
  31408. * The optional parameter `newParent` can be any Node object (default `null`).
  31409. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  31410. * 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.
  31411. */
  31412. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  31413. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31414. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  31415. };
  31416. /**
  31417. * Releases resources associated with this mesh.
  31418. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  31419. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  31420. */
  31421. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  31422. var _this = this;
  31423. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  31424. this.morphTargetManager = null;
  31425. if (this._geometry) {
  31426. this._geometry.releaseForMesh(this, true);
  31427. }
  31428. // Sources
  31429. var meshes = this.getScene().meshes;
  31430. meshes.forEach(function (abstractMesh) {
  31431. var mesh = abstractMesh;
  31432. if (mesh._source && mesh._source === _this) {
  31433. mesh._source = null;
  31434. }
  31435. });
  31436. this._source = null;
  31437. // Instances
  31438. if (this._instancesBuffer) {
  31439. this._instancesBuffer.dispose();
  31440. this._instancesBuffer = null;
  31441. }
  31442. while (this.instances.length) {
  31443. this.instances[0].dispose();
  31444. }
  31445. // Effect layers.
  31446. var effectLayers = this.getScene().effectLayers;
  31447. for (var i = 0; i < effectLayers.length; i++) {
  31448. var effectLayer = effectLayers[i];
  31449. if (effectLayer) {
  31450. effectLayer._disposeMesh(this);
  31451. }
  31452. }
  31453. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  31454. };
  31455. /**
  31456. * Modifies the mesh geometry according to a displacement map.
  31457. * 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.
  31458. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  31459. * This method returns nothing.
  31460. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  31461. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  31462. * 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.
  31463. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  31464. * The parameter `uvScale` is an optional vector2 used to scale UV.
  31465. *
  31466. * Returns the Mesh.
  31467. */
  31468. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  31469. var _this = this;
  31470. var scene = this.getScene();
  31471. var onload = function (img) {
  31472. // Getting height map data
  31473. var canvas = document.createElement("canvas");
  31474. var context = canvas.getContext("2d");
  31475. var heightMapWidth = img.width;
  31476. var heightMapHeight = img.height;
  31477. canvas.width = heightMapWidth;
  31478. canvas.height = heightMapHeight;
  31479. context.drawImage(img, 0, 0);
  31480. // Create VertexData from map data
  31481. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  31482. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  31483. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  31484. //execute success callback, if set
  31485. if (onSuccess) {
  31486. onSuccess(_this);
  31487. }
  31488. };
  31489. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  31490. return this;
  31491. };
  31492. /**
  31493. * Modifies the mesh geometry according to a displacementMap buffer.
  31494. * 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.
  31495. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  31496. * This method returns nothing.
  31497. * 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.
  31498. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  31499. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  31500. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  31501. * The parameter `uvScale` is an optional vector2 used to scale UV.
  31502. *
  31503. * Returns the Mesh.
  31504. */
  31505. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  31506. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  31507. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  31508. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31509. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  31510. return this;
  31511. }
  31512. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31513. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31514. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31515. var position = BABYLON.Vector3.Zero();
  31516. var normal = BABYLON.Vector3.Zero();
  31517. var uv = BABYLON.Vector2.Zero();
  31518. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  31519. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  31520. for (var index = 0; index < positions.length; index += 3) {
  31521. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  31522. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  31523. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  31524. // Compute height
  31525. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  31526. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  31527. var pos = (u + v * heightMapWidth) * 4;
  31528. var r = buffer[pos] / 255.0;
  31529. var g = buffer[pos + 1] / 255.0;
  31530. var b = buffer[pos + 2] / 255.0;
  31531. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  31532. normal.normalize();
  31533. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  31534. position = position.add(normal);
  31535. position.toArray(positions, index);
  31536. }
  31537. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  31538. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  31539. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  31540. return this;
  31541. };
  31542. /**
  31543. * Modify the mesh to get a flat shading rendering.
  31544. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  31545. * This method returns the Mesh.
  31546. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  31547. */
  31548. Mesh.prototype.convertToFlatShadedMesh = function () {
  31549. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  31550. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  31551. var kinds = this.getVerticesDataKinds();
  31552. var vbs = {};
  31553. var data = {};
  31554. var newdata = {};
  31555. var updatableNormals = false;
  31556. var kindIndex;
  31557. var kind;
  31558. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  31559. kind = kinds[kindIndex];
  31560. var vertexBuffer = this.getVertexBuffer(kind);
  31561. if (kind === BABYLON.VertexBuffer.NormalKind) {
  31562. updatableNormals = vertexBuffer.isUpdatable();
  31563. kinds.splice(kindIndex, 1);
  31564. kindIndex--;
  31565. continue;
  31566. }
  31567. vbs[kind] = vertexBuffer;
  31568. data[kind] = vbs[kind].getData();
  31569. newdata[kind] = [];
  31570. }
  31571. // Save previous submeshes
  31572. var previousSubmeshes = this.subMeshes.slice(0);
  31573. var indices = this.getIndices();
  31574. var totalIndices = this.getTotalIndices();
  31575. // Generating unique vertices per face
  31576. var index;
  31577. for (index = 0; index < totalIndices; index++) {
  31578. var vertexIndex = indices[index];
  31579. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  31580. kind = kinds[kindIndex];
  31581. var stride = vbs[kind].getStrideSize();
  31582. for (var offset = 0; offset < stride; offset++) {
  31583. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  31584. }
  31585. }
  31586. }
  31587. // Updating faces & normal
  31588. var normals = [];
  31589. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  31590. for (index = 0; index < totalIndices; index += 3) {
  31591. indices[index] = index;
  31592. indices[index + 1] = index + 1;
  31593. indices[index + 2] = index + 2;
  31594. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  31595. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  31596. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  31597. var p1p2 = p1.subtract(p2);
  31598. var p3p2 = p3.subtract(p2);
  31599. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  31600. // Store same normals for every vertex
  31601. for (var localIndex = 0; localIndex < 3; localIndex++) {
  31602. normals.push(normal.x);
  31603. normals.push(normal.y);
  31604. normals.push(normal.z);
  31605. }
  31606. }
  31607. this.setIndices(indices);
  31608. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  31609. // Updating vertex buffers
  31610. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  31611. kind = kinds[kindIndex];
  31612. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  31613. }
  31614. // Updating submeshes
  31615. this.releaseSubMeshes();
  31616. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  31617. var previousOne = previousSubmeshes[submeshIndex];
  31618. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  31619. }
  31620. this.synchronizeInstances();
  31621. return this;
  31622. };
  31623. /**
  31624. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  31625. * In other words, more vertices, no more indices and a single bigger VBO.
  31626. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  31627. * Returns the Mesh.
  31628. */
  31629. Mesh.prototype.convertToUnIndexedMesh = function () {
  31630. /// <summary>Remove indices by unfolding faces into buffers</summary>
  31631. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  31632. var kinds = this.getVerticesDataKinds();
  31633. var vbs = {};
  31634. var data = {};
  31635. var newdata = {};
  31636. var kindIndex;
  31637. var kind;
  31638. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  31639. kind = kinds[kindIndex];
  31640. var vertexBuffer = this.getVertexBuffer(kind);
  31641. vbs[kind] = vertexBuffer;
  31642. data[kind] = vbs[kind].getData();
  31643. newdata[kind] = [];
  31644. }
  31645. // Save previous submeshes
  31646. var previousSubmeshes = this.subMeshes.slice(0);
  31647. var indices = this.getIndices();
  31648. var totalIndices = this.getTotalIndices();
  31649. // Generating unique vertices per face
  31650. var index;
  31651. for (index = 0; index < totalIndices; index++) {
  31652. var vertexIndex = indices[index];
  31653. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  31654. kind = kinds[kindIndex];
  31655. var stride = vbs[kind].getStrideSize();
  31656. for (var offset = 0; offset < stride; offset++) {
  31657. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  31658. }
  31659. }
  31660. }
  31661. // Updating indices
  31662. for (index = 0; index < totalIndices; index += 3) {
  31663. indices[index] = index;
  31664. indices[index + 1] = index + 1;
  31665. indices[index + 2] = index + 2;
  31666. }
  31667. this.setIndices(indices);
  31668. // Updating vertex buffers
  31669. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  31670. kind = kinds[kindIndex];
  31671. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  31672. }
  31673. // Updating submeshes
  31674. this.releaseSubMeshes();
  31675. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  31676. var previousOne = previousSubmeshes[submeshIndex];
  31677. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  31678. }
  31679. this._unIndexed = true;
  31680. this.synchronizeInstances();
  31681. return this;
  31682. };
  31683. /**
  31684. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  31685. * This method returns the Mesh.
  31686. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  31687. */
  31688. Mesh.prototype.flipFaces = function (flipNormals) {
  31689. if (flipNormals === void 0) { flipNormals = false; }
  31690. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  31691. var i;
  31692. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  31693. for (i = 0; i < vertex_data.normals.length; i++) {
  31694. vertex_data.normals[i] *= -1;
  31695. }
  31696. }
  31697. if (vertex_data.indices) {
  31698. var temp;
  31699. for (i = 0; i < vertex_data.indices.length; i += 3) {
  31700. // reassign indices
  31701. temp = vertex_data.indices[i + 1];
  31702. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  31703. vertex_data.indices[i + 2] = temp;
  31704. }
  31705. }
  31706. vertex_data.applyToMesh(this);
  31707. return this;
  31708. };
  31709. // Instances
  31710. /**
  31711. * Creates a new InstancedMesh object from the mesh model.
  31712. * An instance shares the same properties and the same material than its model.
  31713. * Only these properties of each instance can then be set individually :
  31714. * - position
  31715. * - rotation
  31716. * - rotationQuaternion
  31717. * - setPivotMatrix
  31718. * - scaling
  31719. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  31720. * Warning : this method is not supported for Line mesh and LineSystem
  31721. */
  31722. Mesh.prototype.createInstance = function (name) {
  31723. return new BABYLON.InstancedMesh(name, this);
  31724. };
  31725. /**
  31726. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  31727. * After this call, all the mesh instances have the same submeshes than the current mesh.
  31728. * This method returns the Mesh.
  31729. */
  31730. Mesh.prototype.synchronizeInstances = function () {
  31731. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  31732. var instance = this.instances[instanceIndex];
  31733. instance._syncSubMeshes();
  31734. }
  31735. return this;
  31736. };
  31737. /**
  31738. * Simplify the mesh according to the given array of settings.
  31739. * Function will return immediately and will simplify async. It returns the Mesh.
  31740. * @param settings a collection of simplification settings.
  31741. * @param parallelProcessing should all levels calculate parallel or one after the other.
  31742. * @param type the type of simplification to run.
  31743. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  31744. */
  31745. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  31746. if (parallelProcessing === void 0) { parallelProcessing = true; }
  31747. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  31748. this.getScene().simplificationQueue.addTask({
  31749. settings: settings,
  31750. parallelProcessing: parallelProcessing,
  31751. mesh: this,
  31752. simplificationType: simplificationType,
  31753. successCallback: successCallback
  31754. });
  31755. return this;
  31756. };
  31757. /**
  31758. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  31759. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  31760. * This should be used together with the simplification to avoid disappearing triangles.
  31761. * Returns the Mesh.
  31762. * @param successCallback an optional success callback to be called after the optimization finished.
  31763. */
  31764. Mesh.prototype.optimizeIndices = function (successCallback) {
  31765. var _this = this;
  31766. var indices = this.getIndices();
  31767. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31768. if (!positions || !indices) {
  31769. return this;
  31770. }
  31771. var vectorPositions = new Array();
  31772. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  31773. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  31774. }
  31775. var dupes = new Array();
  31776. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  31777. var realPos = vectorPositions.length - 1 - iteration;
  31778. var testedPosition = vectorPositions[realPos];
  31779. for (var j = 0; j < realPos; ++j) {
  31780. var againstPosition = vectorPositions[j];
  31781. if (testedPosition.equals(againstPosition)) {
  31782. dupes[realPos] = j;
  31783. break;
  31784. }
  31785. }
  31786. }, function () {
  31787. for (var i = 0; i < indices.length; ++i) {
  31788. indices[i] = dupes[indices[i]] || indices[i];
  31789. }
  31790. //indices are now reordered
  31791. var originalSubMeshes = _this.subMeshes.slice(0);
  31792. _this.setIndices(indices);
  31793. _this.subMeshes = originalSubMeshes;
  31794. if (successCallback) {
  31795. successCallback(_this);
  31796. }
  31797. });
  31798. return this;
  31799. };
  31800. Mesh.prototype.serialize = function (serializationObject) {
  31801. serializationObject.name = this.name;
  31802. serializationObject.id = this.id;
  31803. serializationObject.type = this.getClassName();
  31804. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  31805. serializationObject.tags = BABYLON.Tags.GetTags(this);
  31806. }
  31807. serializationObject.position = this.position.asArray();
  31808. if (this.rotationQuaternion) {
  31809. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  31810. }
  31811. else if (this.rotation) {
  31812. serializationObject.rotation = this.rotation.asArray();
  31813. }
  31814. serializationObject.scaling = this.scaling.asArray();
  31815. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  31816. serializationObject.isEnabled = this.isEnabled(false);
  31817. serializationObject.isVisible = this.isVisible;
  31818. serializationObject.infiniteDistance = this.infiniteDistance;
  31819. serializationObject.pickable = this.isPickable;
  31820. serializationObject.receiveShadows = this.receiveShadows;
  31821. serializationObject.billboardMode = this.billboardMode;
  31822. serializationObject.visibility = this.visibility;
  31823. serializationObject.checkCollisions = this.checkCollisions;
  31824. serializationObject.isBlocker = this.isBlocker;
  31825. // Parent
  31826. if (this.parent) {
  31827. serializationObject.parentId = this.parent.id;
  31828. }
  31829. // Geometry
  31830. serializationObject.isUnIndexed = this.isUnIndexed;
  31831. var geometry = this._geometry;
  31832. if (geometry) {
  31833. var geometryId = geometry.id;
  31834. serializationObject.geometryId = geometryId;
  31835. // SubMeshes
  31836. serializationObject.subMeshes = [];
  31837. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  31838. var subMesh = this.subMeshes[subIndex];
  31839. serializationObject.subMeshes.push({
  31840. materialIndex: subMesh.materialIndex,
  31841. verticesStart: subMesh.verticesStart,
  31842. verticesCount: subMesh.verticesCount,
  31843. indexStart: subMesh.indexStart,
  31844. indexCount: subMesh.indexCount
  31845. });
  31846. }
  31847. }
  31848. // Material
  31849. if (this.material) {
  31850. serializationObject.materialId = this.material.id;
  31851. }
  31852. else {
  31853. this.material = null;
  31854. }
  31855. // Morph targets
  31856. if (this.morphTargetManager) {
  31857. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  31858. }
  31859. // Skeleton
  31860. if (this.skeleton) {
  31861. serializationObject.skeletonId = this.skeleton.id;
  31862. }
  31863. // Physics
  31864. //TODO implement correct serialization for physics impostors.
  31865. var impostor = this.getPhysicsImpostor();
  31866. if (impostor) {
  31867. serializationObject.physicsMass = impostor.getParam("mass");
  31868. serializationObject.physicsFriction = impostor.getParam("friction");
  31869. serializationObject.physicsRestitution = impostor.getParam("mass");
  31870. serializationObject.physicsImpostor = impostor.type;
  31871. }
  31872. // Metadata
  31873. if (this.metadata) {
  31874. serializationObject.metadata = this.metadata;
  31875. }
  31876. // Instances
  31877. serializationObject.instances = [];
  31878. for (var index = 0; index < this.instances.length; index++) {
  31879. var instance = this.instances[index];
  31880. var serializationInstance = {
  31881. name: instance.name,
  31882. id: instance.id,
  31883. position: instance.position.asArray(),
  31884. scaling: instance.scaling.asArray()
  31885. };
  31886. if (instance.rotationQuaternion) {
  31887. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  31888. }
  31889. else if (instance.rotation) {
  31890. serializationInstance.rotation = instance.rotation.asArray();
  31891. }
  31892. serializationObject.instances.push(serializationInstance);
  31893. // Animations
  31894. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  31895. serializationInstance.ranges = instance.serializeAnimationRanges();
  31896. }
  31897. //
  31898. // Animations
  31899. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  31900. serializationObject.ranges = this.serializeAnimationRanges();
  31901. // Layer mask
  31902. serializationObject.layerMask = this.layerMask;
  31903. // Alpha
  31904. serializationObject.alphaIndex = this.alphaIndex;
  31905. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  31906. // Overlay
  31907. serializationObject.overlayAlpha = this.overlayAlpha;
  31908. serializationObject.overlayColor = this.overlayColor.asArray();
  31909. serializationObject.renderOverlay = this.renderOverlay;
  31910. // Fog
  31911. serializationObject.applyFog = this.applyFog;
  31912. // Action Manager
  31913. if (this.actionManager) {
  31914. serializationObject.actions = this.actionManager.serialize(this.name);
  31915. }
  31916. };
  31917. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  31918. if (!this.geometry) {
  31919. return;
  31920. }
  31921. this._markSubMeshesAsAttributesDirty();
  31922. var morphTargetManager = this._morphTargetManager;
  31923. if (morphTargetManager && morphTargetManager.vertexCount) {
  31924. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  31925. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  31926. this.morphTargetManager = null;
  31927. return;
  31928. }
  31929. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  31930. var morphTarget = morphTargetManager.getActiveTarget(index);
  31931. var positions = morphTarget.getPositions();
  31932. if (!positions) {
  31933. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  31934. return;
  31935. }
  31936. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  31937. var normals = morphTarget.getNormals();
  31938. if (normals) {
  31939. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  31940. }
  31941. var tangents = morphTarget.getTangents();
  31942. if (tangents) {
  31943. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  31944. }
  31945. }
  31946. }
  31947. else {
  31948. var index = 0;
  31949. // Positions
  31950. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  31951. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  31952. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  31953. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  31954. }
  31955. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  31956. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  31957. }
  31958. index++;
  31959. }
  31960. }
  31961. };
  31962. // Statics
  31963. /**
  31964. * Returns a new Mesh object parsed from the source provided.
  31965. * The parameter `parsedMesh` is the source.
  31966. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  31967. */
  31968. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  31969. var mesh;
  31970. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  31971. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  31972. }
  31973. else {
  31974. mesh = new Mesh(parsedMesh.name, scene);
  31975. }
  31976. mesh.id = parsedMesh.id;
  31977. if (BABYLON.Tags) {
  31978. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  31979. }
  31980. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  31981. if (parsedMesh.metadata !== undefined) {
  31982. mesh.metadata = parsedMesh.metadata;
  31983. }
  31984. if (parsedMesh.rotationQuaternion) {
  31985. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  31986. }
  31987. else if (parsedMesh.rotation) {
  31988. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  31989. }
  31990. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  31991. if (parsedMesh.localMatrix) {
  31992. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  31993. }
  31994. else if (parsedMesh.pivotMatrix) {
  31995. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  31996. }
  31997. mesh.setEnabled(parsedMesh.isEnabled);
  31998. mesh.isVisible = parsedMesh.isVisible;
  31999. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  32000. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  32001. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  32002. if (parsedMesh.applyFog !== undefined) {
  32003. mesh.applyFog = parsedMesh.applyFog;
  32004. }
  32005. if (parsedMesh.pickable !== undefined) {
  32006. mesh.isPickable = parsedMesh.pickable;
  32007. }
  32008. if (parsedMesh.alphaIndex !== undefined) {
  32009. mesh.alphaIndex = parsedMesh.alphaIndex;
  32010. }
  32011. mesh.receiveShadows = parsedMesh.receiveShadows;
  32012. mesh.billboardMode = parsedMesh.billboardMode;
  32013. if (parsedMesh.visibility !== undefined) {
  32014. mesh.visibility = parsedMesh.visibility;
  32015. }
  32016. mesh.checkCollisions = parsedMesh.checkCollisions;
  32017. if (parsedMesh.isBlocker !== undefined) {
  32018. mesh.isBlocker = parsedMesh.isBlocker;
  32019. }
  32020. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  32021. // freezeWorldMatrix
  32022. if (parsedMesh.freezeWorldMatrix) {
  32023. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  32024. }
  32025. // Parent
  32026. if (parsedMesh.parentId) {
  32027. mesh._waitingParentId = parsedMesh.parentId;
  32028. }
  32029. // Actions
  32030. if (parsedMesh.actions !== undefined) {
  32031. mesh._waitingActions = parsedMesh.actions;
  32032. }
  32033. // Overlay
  32034. if (parsedMesh.overlayAlpha !== undefined) {
  32035. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  32036. }
  32037. if (parsedMesh.overlayColor !== undefined) {
  32038. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  32039. }
  32040. if (parsedMesh.renderOverlay !== undefined) {
  32041. mesh.renderOverlay = parsedMesh.renderOverlay;
  32042. }
  32043. // Geometry
  32044. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  32045. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  32046. if (parsedMesh.delayLoadingFile) {
  32047. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32048. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  32049. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  32050. if (parsedMesh._binaryInfo) {
  32051. mesh._binaryInfo = parsedMesh._binaryInfo;
  32052. }
  32053. mesh._delayInfo = [];
  32054. if (parsedMesh.hasUVs) {
  32055. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  32056. }
  32057. if (parsedMesh.hasUVs2) {
  32058. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  32059. }
  32060. if (parsedMesh.hasUVs3) {
  32061. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  32062. }
  32063. if (parsedMesh.hasUVs4) {
  32064. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  32065. }
  32066. if (parsedMesh.hasUVs5) {
  32067. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  32068. }
  32069. if (parsedMesh.hasUVs6) {
  32070. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  32071. }
  32072. if (parsedMesh.hasColors) {
  32073. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  32074. }
  32075. if (parsedMesh.hasMatricesIndices) {
  32076. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32077. }
  32078. if (parsedMesh.hasMatricesWeights) {
  32079. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32080. }
  32081. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  32082. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  32083. mesh._checkDelayState();
  32084. }
  32085. }
  32086. else {
  32087. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  32088. }
  32089. // Material
  32090. if (parsedMesh.materialId) {
  32091. mesh.setMaterialByID(parsedMesh.materialId);
  32092. }
  32093. else {
  32094. mesh.material = null;
  32095. }
  32096. // Morph targets
  32097. if (parsedMesh.morphTargetManagerId > -1) {
  32098. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  32099. }
  32100. // Skeleton
  32101. if (parsedMesh.skeletonId > -1) {
  32102. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  32103. if (parsedMesh.numBoneInfluencers) {
  32104. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  32105. }
  32106. }
  32107. // Animations
  32108. if (parsedMesh.animations) {
  32109. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  32110. var parsedAnimation = parsedMesh.animations[animationIndex];
  32111. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32112. }
  32113. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  32114. }
  32115. if (parsedMesh.autoAnimate) {
  32116. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  32117. }
  32118. // Layer Mask
  32119. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  32120. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  32121. }
  32122. else {
  32123. mesh.layerMask = 0x0FFFFFFF;
  32124. }
  32125. // Physics
  32126. if (parsedMesh.physicsImpostor) {
  32127. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  32128. mass: parsedMesh.physicsMass,
  32129. friction: parsedMesh.physicsFriction,
  32130. restitution: parsedMesh.physicsRestitution
  32131. }, scene);
  32132. }
  32133. // Instances
  32134. if (parsedMesh.instances) {
  32135. for (var index = 0; index < parsedMesh.instances.length; index++) {
  32136. var parsedInstance = parsedMesh.instances[index];
  32137. var instance = mesh.createInstance(parsedInstance.name);
  32138. if (parsedInstance.id) {
  32139. instance.id = parsedInstance.id;
  32140. }
  32141. if (BABYLON.Tags) {
  32142. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  32143. }
  32144. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  32145. if (parsedInstance.parentId) {
  32146. instance._waitingParentId = parsedInstance.parentId;
  32147. }
  32148. if (parsedInstance.rotationQuaternion) {
  32149. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  32150. }
  32151. else if (parsedInstance.rotation) {
  32152. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  32153. }
  32154. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  32155. instance.checkCollisions = mesh.checkCollisions;
  32156. if (parsedMesh.animations) {
  32157. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  32158. parsedAnimation = parsedMesh.animations[animationIndex];
  32159. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32160. }
  32161. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  32162. }
  32163. }
  32164. }
  32165. return mesh;
  32166. };
  32167. /**
  32168. * Creates a ribbon mesh.
  32169. * Please consider using the same method from the MeshBuilder class instead.
  32170. * 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.
  32171. *
  32172. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  32173. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  32174. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  32175. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  32176. * 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.
  32177. * 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.
  32178. * 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
  32179. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32180. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32181. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32182. */
  32183. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  32184. if (closeArray === void 0) { closeArray = false; }
  32185. if (updatable === void 0) { updatable = false; }
  32186. return BABYLON.MeshBuilder.CreateRibbon(name, {
  32187. pathArray: pathArray,
  32188. closeArray: closeArray,
  32189. closePath: closePath,
  32190. offset: offset,
  32191. updatable: updatable,
  32192. sideOrientation: sideOrientation,
  32193. instance: instance
  32194. }, scene);
  32195. };
  32196. /**
  32197. * Creates a plane polygonal mesh. By default, this is a disc.
  32198. * Please consider using the same method from the MeshBuilder class instead.
  32199. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  32200. * 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.
  32201. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32202. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32203. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32204. */
  32205. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  32206. if (scene === void 0) { scene = null; }
  32207. var options = {
  32208. radius: radius,
  32209. tessellation: tessellation,
  32210. sideOrientation: sideOrientation,
  32211. updatable: updatable
  32212. };
  32213. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  32214. };
  32215. /**
  32216. * Creates a box mesh.
  32217. * Please consider using the same method from the MeshBuilder class instead.
  32218. * The parameter `size` sets the size (float) of each box side (default 1).
  32219. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32220. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32221. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32222. */
  32223. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  32224. if (scene === void 0) { scene = null; }
  32225. var options = {
  32226. size: size,
  32227. sideOrientation: sideOrientation,
  32228. updatable: updatable
  32229. };
  32230. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  32231. };
  32232. /**
  32233. * Creates a sphere mesh.
  32234. * Please consider using the same method from the MeshBuilder class instead.
  32235. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  32236. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  32237. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32238. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32239. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32240. */
  32241. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  32242. var options = {
  32243. segments: segments,
  32244. diameterX: diameter,
  32245. diameterY: diameter,
  32246. diameterZ: diameter,
  32247. sideOrientation: sideOrientation,
  32248. updatable: updatable
  32249. };
  32250. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  32251. };
  32252. /**
  32253. * Creates a cylinder or a cone mesh.
  32254. * Please consider using the same method from the MeshBuilder class instead.
  32255. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  32256. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  32257. * 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.
  32258. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  32259. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  32260. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32261. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32262. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32263. */
  32264. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  32265. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  32266. if (scene !== undefined) {
  32267. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  32268. updatable = scene;
  32269. }
  32270. scene = subdivisions;
  32271. subdivisions = 1;
  32272. }
  32273. var options = {
  32274. height: height,
  32275. diameterTop: diameterTop,
  32276. diameterBottom: diameterBottom,
  32277. tessellation: tessellation,
  32278. subdivisions: subdivisions,
  32279. sideOrientation: sideOrientation,
  32280. updatable: updatable
  32281. };
  32282. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  32283. };
  32284. // Torus (Code from SharpDX.org)
  32285. /**
  32286. * Creates a torus mesh.
  32287. * Please consider using the same method from the MeshBuilder class instead.
  32288. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  32289. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  32290. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  32291. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32292. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32293. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32294. */
  32295. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  32296. var options = {
  32297. diameter: diameter,
  32298. thickness: thickness,
  32299. tessellation: tessellation,
  32300. sideOrientation: sideOrientation,
  32301. updatable: updatable
  32302. };
  32303. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  32304. };
  32305. /**
  32306. * Creates a torus knot mesh.
  32307. * Please consider using the same method from the MeshBuilder class instead.
  32308. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  32309. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  32310. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  32311. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  32312. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32313. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32314. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32315. */
  32316. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  32317. var options = {
  32318. radius: radius,
  32319. tube: tube,
  32320. radialSegments: radialSegments,
  32321. tubularSegments: tubularSegments,
  32322. p: p,
  32323. q: q,
  32324. sideOrientation: sideOrientation,
  32325. updatable: updatable
  32326. };
  32327. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  32328. };
  32329. /**
  32330. * Creates a line mesh.
  32331. * Please consider using the same method from the MeshBuilder class instead.
  32332. * 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.
  32333. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  32334. * The parameter `points` is an array successive Vector3.
  32335. * 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
  32336. * When updating an instance, remember that only point positions can change, not the number of points.
  32337. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32338. */
  32339. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  32340. if (scene === void 0) { scene = null; }
  32341. if (updatable === void 0) { updatable = false; }
  32342. if (instance === void 0) { instance = null; }
  32343. var options = {
  32344. points: points,
  32345. updatable: updatable,
  32346. instance: instance
  32347. };
  32348. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  32349. };
  32350. /**
  32351. * Creates a dashed line mesh.
  32352. * Please consider using the same method from the MeshBuilder class instead.
  32353. * 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.
  32354. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  32355. * The parameter `points` is an array successive Vector3.
  32356. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  32357. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  32358. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  32359. * 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
  32360. * When updating an instance, remember that only point positions can change, not the number of points.
  32361. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32362. */
  32363. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  32364. if (scene === void 0) { scene = null; }
  32365. var options = {
  32366. points: points,
  32367. dashSize: dashSize,
  32368. gapSize: gapSize,
  32369. dashNb: dashNb,
  32370. updatable: updatable,
  32371. instance: instance
  32372. };
  32373. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  32374. };
  32375. /**
  32376. * Creates a polygon mesh.
  32377. * Please consider using the same method from the MeshBuilder class instead.
  32378. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  32379. * 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.
  32380. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32381. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32382. * Remember you can only change the shape positions, not their number when updating a polygon.
  32383. */
  32384. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  32385. var options = {
  32386. shape: shape,
  32387. holes: holes,
  32388. updatable: updatable,
  32389. sideOrientation: sideOrientation
  32390. };
  32391. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  32392. };
  32393. /**
  32394. * Creates an extruded polygon mesh, with depth in the Y direction.
  32395. * Please consider using the same method from the MeshBuilder class instead.
  32396. */
  32397. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  32398. var options = {
  32399. shape: shape,
  32400. holes: holes,
  32401. depth: depth,
  32402. updatable: updatable,
  32403. sideOrientation: sideOrientation
  32404. };
  32405. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  32406. };
  32407. /**
  32408. * Creates an extruded shape mesh.
  32409. * 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.
  32410. * Please consider using the same method from the MeshBuilder class instead.
  32411. *
  32412. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  32413. * 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
  32414. * extruded along the Z axis.
  32415. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  32416. * 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.
  32417. * The parameter `scale` (float, default 1) is the value to scale the shape.
  32418. * 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
  32419. * 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
  32420. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  32421. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32422. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32423. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32424. */
  32425. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  32426. if (scene === void 0) { scene = null; }
  32427. var options = {
  32428. shape: shape,
  32429. path: path,
  32430. scale: scale,
  32431. rotation: rotation,
  32432. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  32433. sideOrientation: sideOrientation,
  32434. instance: instance,
  32435. updatable: updatable
  32436. };
  32437. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  32438. };
  32439. /**
  32440. * Creates an custom extruded shape mesh.
  32441. * 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.
  32442. * Please consider using the same method from the MeshBuilder class instead.
  32443. *
  32444. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  32445. * 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
  32446. * extruded along the Z axis.
  32447. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  32448. * 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
  32449. * and the distance of this point from the begining of the path :
  32450. * ```javascript
  32451. * var rotationFunction = function(i, distance) {
  32452. * // do things
  32453. * return rotationValue; }
  32454. * ```
  32455. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  32456. * 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
  32457. * and the distance of this point from the begining of the path :
  32458. * ```javascript
  32459. * var scaleFunction = function(i, distance) {
  32460. * // do things
  32461. * return scaleValue;}
  32462. * ```
  32463. * It must returns a float value that will be the scale value applied to the shape on each path point.
  32464. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  32465. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  32466. * 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
  32467. * 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
  32468. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  32469. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32470. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32471. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32472. */
  32473. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  32474. var options = {
  32475. shape: shape,
  32476. path: path,
  32477. scaleFunction: scaleFunction,
  32478. rotationFunction: rotationFunction,
  32479. ribbonCloseArray: ribbonCloseArray,
  32480. ribbonClosePath: ribbonClosePath,
  32481. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  32482. sideOrientation: sideOrientation,
  32483. instance: instance,
  32484. updatable: updatable
  32485. };
  32486. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  32487. };
  32488. /**
  32489. * Creates lathe mesh.
  32490. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  32491. * Please consider using the same method from the MeshBuilder class instead.
  32492. * 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
  32493. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  32494. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  32495. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  32496. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32497. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32498. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32499. */
  32500. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  32501. var options = {
  32502. shape: shape,
  32503. radius: radius,
  32504. tessellation: tessellation,
  32505. sideOrientation: sideOrientation,
  32506. updatable: updatable
  32507. };
  32508. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  32509. };
  32510. /**
  32511. * Creates a plane mesh.
  32512. * Please consider using the same method from the MeshBuilder class instead.
  32513. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  32514. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32515. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32516. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32517. */
  32518. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  32519. var options = {
  32520. size: size,
  32521. width: size,
  32522. height: size,
  32523. sideOrientation: sideOrientation,
  32524. updatable: updatable
  32525. };
  32526. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  32527. };
  32528. /**
  32529. * Creates a ground mesh.
  32530. * Please consider using the same method from the MeshBuilder class instead.
  32531. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  32532. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  32533. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32534. */
  32535. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  32536. var options = {
  32537. width: width,
  32538. height: height,
  32539. subdivisions: subdivisions,
  32540. updatable: updatable
  32541. };
  32542. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  32543. };
  32544. /**
  32545. * Creates a tiled ground mesh.
  32546. * Please consider using the same method from the MeshBuilder class instead.
  32547. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  32548. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  32549. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  32550. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  32551. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  32552. * numbers of subdivisions on the ground width and height of each tile.
  32553. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32554. */
  32555. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  32556. var options = {
  32557. xmin: xmin,
  32558. zmin: zmin,
  32559. xmax: xmax,
  32560. zmax: zmax,
  32561. subdivisions: subdivisions,
  32562. precision: precision,
  32563. updatable: updatable
  32564. };
  32565. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  32566. };
  32567. /**
  32568. * Creates a ground mesh from a height map.
  32569. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  32570. * Please consider using the same method from the MeshBuilder class instead.
  32571. * The parameter `url` sets the URL of the height map image resource.
  32572. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  32573. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  32574. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  32575. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  32576. * 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).
  32577. * This function is passed the newly built mesh :
  32578. * ```javascript
  32579. * function(mesh) { // do things
  32580. * return; }
  32581. * ```
  32582. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32583. */
  32584. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  32585. var options = {
  32586. width: width,
  32587. height: height,
  32588. subdivisions: subdivisions,
  32589. minHeight: minHeight,
  32590. maxHeight: maxHeight,
  32591. updatable: updatable,
  32592. onReady: onReady
  32593. };
  32594. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  32595. };
  32596. /**
  32597. * Creates a tube mesh.
  32598. * 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.
  32599. * Please consider using the same method from the MeshBuilder class instead.
  32600. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  32601. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  32602. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  32603. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  32604. * 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.
  32605. * It must return a radius value (positive float) :
  32606. * ```javascript
  32607. * var radiusFunction = function(i, distance) {
  32608. * // do things
  32609. * return radius; }
  32610. * ```
  32611. * 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
  32612. * 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
  32613. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32614. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32615. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32616. */
  32617. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  32618. var options = {
  32619. path: path,
  32620. radius: radius,
  32621. tessellation: tessellation,
  32622. radiusFunction: radiusFunction,
  32623. arc: 1,
  32624. cap: cap,
  32625. updatable: updatable,
  32626. sideOrientation: sideOrientation,
  32627. instance: instance
  32628. };
  32629. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  32630. };
  32631. /**
  32632. * Creates a polyhedron mesh.
  32633. * Please consider using the same method from the MeshBuilder class instead.
  32634. * 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
  32635. * to choose the wanted type.
  32636. * The parameter `size` (positive float, default 1) sets the polygon size.
  32637. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  32638. * 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`.
  32639. * 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
  32640. * 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)`).
  32641. * 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
  32642. * 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.
  32643. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32644. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32645. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32646. */
  32647. Mesh.CreatePolyhedron = function (name, options, scene) {
  32648. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  32649. };
  32650. /**
  32651. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  32652. * Please consider using the same method from the MeshBuilder class instead.
  32653. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  32654. * 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`).
  32655. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  32656. * 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.
  32657. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32658. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32659. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32660. */
  32661. Mesh.CreateIcoSphere = function (name, options, scene) {
  32662. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  32663. };
  32664. /**
  32665. * Creates a decal mesh.
  32666. * Please consider using the same method from the MeshBuilder class instead.
  32667. * 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.
  32668. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  32669. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  32670. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  32671. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  32672. */
  32673. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  32674. var options = {
  32675. position: position,
  32676. normal: normal,
  32677. size: size,
  32678. angle: angle
  32679. };
  32680. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  32681. };
  32682. // Skeletons
  32683. /**
  32684. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  32685. */
  32686. Mesh.prototype.setPositionsForCPUSkinning = function () {
  32687. if (!this._sourcePositions) {
  32688. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32689. if (!source) {
  32690. return this._sourcePositions;
  32691. }
  32692. this._sourcePositions = new Float32Array(source);
  32693. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  32694. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  32695. }
  32696. }
  32697. return this._sourcePositions;
  32698. };
  32699. /**
  32700. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  32701. */
  32702. Mesh.prototype.setNormalsForCPUSkinning = function () {
  32703. if (!this._sourceNormals) {
  32704. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32705. if (!source) {
  32706. return this._sourceNormals;
  32707. }
  32708. this._sourceNormals = new Float32Array(source);
  32709. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  32710. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  32711. }
  32712. }
  32713. return this._sourceNormals;
  32714. };
  32715. /**
  32716. * Updates the vertex buffer by applying transformation from the bones.
  32717. * Returns the Mesh.
  32718. *
  32719. * @param {skeleton} skeleton to apply
  32720. */
  32721. Mesh.prototype.applySkeleton = function (skeleton) {
  32722. if (!this.geometry) {
  32723. return this;
  32724. }
  32725. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  32726. return this;
  32727. }
  32728. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  32729. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32730. return this;
  32731. }
  32732. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32733. return this;
  32734. }
  32735. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32736. return this;
  32737. }
  32738. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32739. return this;
  32740. }
  32741. if (!this._sourcePositions) {
  32742. var submeshes = this.subMeshes.slice();
  32743. this.setPositionsForCPUSkinning();
  32744. this.subMeshes = submeshes;
  32745. }
  32746. if (!this._sourceNormals) {
  32747. this.setNormalsForCPUSkinning();
  32748. }
  32749. // positionsData checks for not being Float32Array will only pass at most once
  32750. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32751. if (!positionsData) {
  32752. return this;
  32753. }
  32754. if (!(positionsData instanceof Float32Array)) {
  32755. positionsData = new Float32Array(positionsData);
  32756. }
  32757. // normalsData checks for not being Float32Array will only pass at most once
  32758. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32759. if (!normalsData) {
  32760. return this;
  32761. }
  32762. if (!(normalsData instanceof Float32Array)) {
  32763. normalsData = new Float32Array(normalsData);
  32764. }
  32765. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32766. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32767. if (!matricesWeightsData || !matricesIndicesData) {
  32768. return this;
  32769. }
  32770. var needExtras = this.numBoneInfluencers > 4;
  32771. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  32772. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  32773. var skeletonMatrices = skeleton.getTransformMatrices(this);
  32774. var tempVector3 = BABYLON.Vector3.Zero();
  32775. var finalMatrix = new BABYLON.Matrix();
  32776. var tempMatrix = new BABYLON.Matrix();
  32777. var matWeightIdx = 0;
  32778. var inf;
  32779. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  32780. var weight;
  32781. for (inf = 0; inf < 4; inf++) {
  32782. weight = matricesWeightsData[matWeightIdx + inf];
  32783. if (weight > 0) {
  32784. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32785. finalMatrix.addToSelf(tempMatrix);
  32786. }
  32787. else
  32788. break;
  32789. }
  32790. if (needExtras) {
  32791. for (inf = 0; inf < 4; inf++) {
  32792. weight = matricesWeightsExtraData[matWeightIdx + inf];
  32793. if (weight > 0) {
  32794. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32795. finalMatrix.addToSelf(tempMatrix);
  32796. }
  32797. else
  32798. break;
  32799. }
  32800. }
  32801. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  32802. tempVector3.toArray(positionsData, index);
  32803. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  32804. tempVector3.toArray(normalsData, index);
  32805. finalMatrix.reset();
  32806. }
  32807. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  32808. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  32809. return this;
  32810. };
  32811. // Tools
  32812. /**
  32813. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  32814. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  32815. */
  32816. Mesh.MinMax = function (meshes) {
  32817. var minVector = null;
  32818. var maxVector = null;
  32819. meshes.forEach(function (mesh, index, array) {
  32820. var boundingInfo = mesh.getBoundingInfo();
  32821. var boundingBox = boundingInfo.boundingBox;
  32822. if (!minVector || !maxVector) {
  32823. minVector = boundingBox.minimumWorld;
  32824. maxVector = boundingBox.maximumWorld;
  32825. }
  32826. else {
  32827. minVector.minimizeInPlace(boundingBox.minimumWorld);
  32828. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  32829. }
  32830. });
  32831. if (!minVector || !maxVector) {
  32832. return {
  32833. min: BABYLON.Vector3.Zero(),
  32834. max: BABYLON.Vector3.Zero()
  32835. };
  32836. }
  32837. return {
  32838. min: minVector,
  32839. max: maxVector
  32840. };
  32841. };
  32842. /**
  32843. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  32844. */
  32845. Mesh.Center = function (meshesOrMinMaxVector) {
  32846. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  32847. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  32848. };
  32849. /**
  32850. * Merge the array of meshes into a single mesh for performance reasons.
  32851. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  32852. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  32853. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  32854. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  32855. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  32856. */
  32857. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  32858. if (disposeSource === void 0) { disposeSource = true; }
  32859. var index;
  32860. if (!allow32BitsIndices) {
  32861. var totalVertices = 0;
  32862. // Counting vertices
  32863. for (index = 0; index < meshes.length; index++) {
  32864. if (meshes[index]) {
  32865. totalVertices += meshes[index].getTotalVertices();
  32866. if (totalVertices > 65536) {
  32867. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  32868. return null;
  32869. }
  32870. }
  32871. }
  32872. }
  32873. // Merge
  32874. var vertexData = null;
  32875. var otherVertexData;
  32876. var indiceArray = new Array();
  32877. var source = null;
  32878. for (index = 0; index < meshes.length; index++) {
  32879. if (meshes[index]) {
  32880. meshes[index].computeWorldMatrix(true);
  32881. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  32882. otherVertexData.transform(meshes[index].getWorldMatrix());
  32883. if (vertexData) {
  32884. vertexData.merge(otherVertexData);
  32885. }
  32886. else {
  32887. vertexData = otherVertexData;
  32888. source = meshes[index];
  32889. }
  32890. if (subdivideWithSubMeshes) {
  32891. indiceArray.push(meshes[index].getTotalIndices());
  32892. }
  32893. }
  32894. }
  32895. source = source;
  32896. if (!meshSubclass) {
  32897. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  32898. }
  32899. vertexData.applyToMesh(meshSubclass);
  32900. // Setting properties
  32901. meshSubclass.material = source.material;
  32902. meshSubclass.checkCollisions = source.checkCollisions;
  32903. // Cleaning
  32904. if (disposeSource) {
  32905. for (index = 0; index < meshes.length; index++) {
  32906. if (meshes[index]) {
  32907. meshes[index].dispose();
  32908. }
  32909. }
  32910. }
  32911. // Subdivide
  32912. if (subdivideWithSubMeshes) {
  32913. //-- Suppresions du submesh global
  32914. meshSubclass.releaseSubMeshes();
  32915. index = 0;
  32916. var offset = 0;
  32917. //-- aplique la subdivision en fonction du tableau d'indices
  32918. while (index < indiceArray.length) {
  32919. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  32920. offset += indiceArray[index];
  32921. index++;
  32922. }
  32923. }
  32924. return meshSubclass;
  32925. };
  32926. // Consts
  32927. Mesh._FRONTSIDE = 0;
  32928. Mesh._BACKSIDE = 1;
  32929. Mesh._DOUBLESIDE = 2;
  32930. Mesh._DEFAULTSIDE = 0;
  32931. Mesh._NO_CAP = 0;
  32932. Mesh._CAP_START = 1;
  32933. Mesh._CAP_END = 2;
  32934. Mesh._CAP_ALL = 3;
  32935. return Mesh;
  32936. }(BABYLON.AbstractMesh));
  32937. BABYLON.Mesh = Mesh;
  32938. })(BABYLON || (BABYLON = {}));
  32939. //# sourceMappingURL=babylon.mesh.js.map
  32940. "use strict";
  32941. var BABYLON;
  32942. (function (BABYLON) {
  32943. var BaseSubMesh = /** @class */ (function () {
  32944. function BaseSubMesh() {
  32945. }
  32946. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  32947. get: function () {
  32948. return this._materialEffect;
  32949. },
  32950. enumerable: true,
  32951. configurable: true
  32952. });
  32953. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  32954. if (defines === void 0) { defines = null; }
  32955. if (this._materialEffect === effect) {
  32956. if (!effect) {
  32957. this._materialDefines = null;
  32958. }
  32959. return;
  32960. }
  32961. this._materialDefines = defines;
  32962. this._materialEffect = effect;
  32963. };
  32964. return BaseSubMesh;
  32965. }());
  32966. BABYLON.BaseSubMesh = BaseSubMesh;
  32967. var SubMesh = /** @class */ (function (_super) {
  32968. __extends(SubMesh, _super);
  32969. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  32970. if (createBoundingBox === void 0) { createBoundingBox = true; }
  32971. var _this = _super.call(this) || this;
  32972. _this.materialIndex = materialIndex;
  32973. _this.verticesStart = verticesStart;
  32974. _this.verticesCount = verticesCount;
  32975. _this.indexStart = indexStart;
  32976. _this.indexCount = indexCount;
  32977. _this._renderId = 0;
  32978. _this._mesh = mesh;
  32979. _this._renderingMesh = renderingMesh || mesh;
  32980. mesh.subMeshes.push(_this);
  32981. _this._trianglePlanes = [];
  32982. _this._id = mesh.subMeshes.length - 1;
  32983. if (createBoundingBox) {
  32984. _this.refreshBoundingInfo();
  32985. mesh.computeWorldMatrix(true);
  32986. }
  32987. return _this;
  32988. }
  32989. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  32990. if (createBoundingBox === void 0) { createBoundingBox = true; }
  32991. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  32992. };
  32993. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  32994. get: function () {
  32995. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  32996. },
  32997. enumerable: true,
  32998. configurable: true
  32999. });
  33000. /**
  33001. * Returns the submesh BoudingInfo object.
  33002. */
  33003. SubMesh.prototype.getBoundingInfo = function () {
  33004. if (this.IsGlobal) {
  33005. return this._mesh.getBoundingInfo();
  33006. }
  33007. return this._boundingInfo;
  33008. };
  33009. /**
  33010. * Sets the submesh BoundingInfo.
  33011. * Return the SubMesh.
  33012. */
  33013. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  33014. this._boundingInfo = boundingInfo;
  33015. return this;
  33016. };
  33017. /**
  33018. * Returns the mesh of the current submesh.
  33019. */
  33020. SubMesh.prototype.getMesh = function () {
  33021. return this._mesh;
  33022. };
  33023. /**
  33024. * Returns the rendering mesh of the submesh.
  33025. */
  33026. SubMesh.prototype.getRenderingMesh = function () {
  33027. return this._renderingMesh;
  33028. };
  33029. /**
  33030. * Returns the submesh material.
  33031. */
  33032. SubMesh.prototype.getMaterial = function () {
  33033. var rootMaterial = this._renderingMesh.material;
  33034. if (rootMaterial === null || rootMaterial === undefined) {
  33035. return this._mesh.getScene().defaultMaterial;
  33036. }
  33037. else if (rootMaterial.getSubMaterial) {
  33038. var multiMaterial = rootMaterial;
  33039. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  33040. if (this._currentMaterial !== effectiveMaterial) {
  33041. this._currentMaterial = effectiveMaterial;
  33042. this._materialDefines = null;
  33043. }
  33044. return effectiveMaterial;
  33045. }
  33046. return rootMaterial;
  33047. };
  33048. // Methods
  33049. /**
  33050. * Sets a new updated BoundingInfo object to the submesh.
  33051. * Returns the SubMesh.
  33052. */
  33053. SubMesh.prototype.refreshBoundingInfo = function () {
  33054. this._lastColliderWorldVertices = null;
  33055. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  33056. return this;
  33057. }
  33058. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33059. if (!data) {
  33060. this._boundingInfo = this._mesh.getBoundingInfo();
  33061. return this;
  33062. }
  33063. var indices = this._renderingMesh.getIndices();
  33064. var extend;
  33065. //is this the only submesh?
  33066. if (this.indexStart === 0 && this.indexCount === indices.length) {
  33067. var boundingInfo = this._renderingMesh.getBoundingInfo();
  33068. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  33069. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  33070. }
  33071. else {
  33072. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  33073. }
  33074. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  33075. return this;
  33076. };
  33077. SubMesh.prototype._checkCollision = function (collider) {
  33078. var boundingInfo = this.getBoundingInfo();
  33079. return boundingInfo._checkCollision(collider);
  33080. };
  33081. /**
  33082. * Updates the submesh BoundingInfo.
  33083. * Returns the Submesh.
  33084. */
  33085. SubMesh.prototype.updateBoundingInfo = function (world) {
  33086. var boundingInfo = this.getBoundingInfo();
  33087. if (!boundingInfo) {
  33088. this.refreshBoundingInfo();
  33089. boundingInfo = this.getBoundingInfo();
  33090. }
  33091. boundingInfo.update(world);
  33092. return this;
  33093. };
  33094. /**
  33095. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  33096. * Boolean returned.
  33097. */
  33098. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  33099. var boundingInfo = this.getBoundingInfo();
  33100. if (!boundingInfo) {
  33101. return false;
  33102. }
  33103. return boundingInfo.isInFrustum(frustumPlanes);
  33104. };
  33105. /**
  33106. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  33107. * Boolean returned.
  33108. */
  33109. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  33110. var boundingInfo = this.getBoundingInfo();
  33111. if (!boundingInfo) {
  33112. return false;
  33113. }
  33114. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  33115. };
  33116. /**
  33117. * Renders the submesh.
  33118. * Returns it.
  33119. */
  33120. SubMesh.prototype.render = function (enableAlphaMode) {
  33121. this._renderingMesh.render(this, enableAlphaMode);
  33122. return this;
  33123. };
  33124. /**
  33125. * Returns a new Index Buffer.
  33126. * Type returned : WebGLBuffer.
  33127. */
  33128. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  33129. if (!this._linesIndexBuffer) {
  33130. var linesIndices = [];
  33131. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  33132. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  33133. }
  33134. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  33135. this.linesIndexCount = linesIndices.length;
  33136. }
  33137. return this._linesIndexBuffer;
  33138. };
  33139. /**
  33140. * True is the passed Ray intersects the submesh bounding box.
  33141. * Boolean returned.
  33142. */
  33143. SubMesh.prototype.canIntersects = function (ray) {
  33144. var boundingInfo = this.getBoundingInfo();
  33145. if (!boundingInfo) {
  33146. return false;
  33147. }
  33148. return ray.intersectsBox(boundingInfo.boundingBox);
  33149. };
  33150. /**
  33151. * Returns an object IntersectionInfo.
  33152. */
  33153. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  33154. var intersectInfo = null;
  33155. var material = this.getMaterial();
  33156. if (!material) {
  33157. return null;
  33158. }
  33159. switch (material.fillMode) {
  33160. case BABYLON.Material.PointListDrawMode:
  33161. case BABYLON.Material.LineListDrawMode:
  33162. case BABYLON.Material.LineLoopDrawMode:
  33163. case BABYLON.Material.LineStripDrawMode:
  33164. case BABYLON.Material.TriangleFanDrawMode:
  33165. case BABYLON.Material.TriangleStripDrawMode:
  33166. return null;
  33167. }
  33168. // LineMesh first as it's also a Mesh...
  33169. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  33170. var lineMesh = this._mesh;
  33171. // Line test
  33172. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  33173. var p0 = positions[indices[index]];
  33174. var p1 = positions[indices[index + 1]];
  33175. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  33176. if (length < 0) {
  33177. continue;
  33178. }
  33179. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  33180. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  33181. if (fastCheck) {
  33182. break;
  33183. }
  33184. }
  33185. }
  33186. }
  33187. else {
  33188. // Triangles test
  33189. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  33190. var p0 = positions[indices[index]];
  33191. var p1 = positions[indices[index + 1]];
  33192. var p2 = positions[indices[index + 2]];
  33193. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  33194. if (currentIntersectInfo) {
  33195. if (currentIntersectInfo.distance < 0) {
  33196. continue;
  33197. }
  33198. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  33199. intersectInfo = currentIntersectInfo;
  33200. intersectInfo.faceId = index / 3;
  33201. if (fastCheck) {
  33202. break;
  33203. }
  33204. }
  33205. }
  33206. }
  33207. }
  33208. return intersectInfo;
  33209. };
  33210. SubMesh.prototype._rebuild = function () {
  33211. if (this._linesIndexBuffer) {
  33212. this._linesIndexBuffer = null;
  33213. }
  33214. };
  33215. // Clone
  33216. /**
  33217. * Creates a new Submesh from the passed Mesh.
  33218. */
  33219. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  33220. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  33221. if (!this.IsGlobal) {
  33222. var boundingInfo = this.getBoundingInfo();
  33223. if (!boundingInfo) {
  33224. return result;
  33225. }
  33226. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  33227. }
  33228. return result;
  33229. };
  33230. // Dispose
  33231. /**
  33232. * Disposes the Submesh.
  33233. * Returns nothing.
  33234. */
  33235. SubMesh.prototype.dispose = function () {
  33236. if (this._linesIndexBuffer) {
  33237. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  33238. this._linesIndexBuffer = null;
  33239. }
  33240. // Remove from mesh
  33241. var index = this._mesh.subMeshes.indexOf(this);
  33242. this._mesh.subMeshes.splice(index, 1);
  33243. };
  33244. // Statics
  33245. /**
  33246. * Creates a new Submesh from the passed parameters :
  33247. * - materialIndex (integer) : the index of the main mesh material.
  33248. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  33249. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  33250. * - mesh (Mesh) : the main mesh to create the submesh from.
  33251. * - renderingMesh (optional Mesh) : rendering mesh.
  33252. */
  33253. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  33254. var minVertexIndex = Number.MAX_VALUE;
  33255. var maxVertexIndex = -Number.MAX_VALUE;
  33256. renderingMesh = (renderingMesh || mesh);
  33257. var indices = renderingMesh.getIndices();
  33258. for (var index = startIndex; index < startIndex + indexCount; index++) {
  33259. var vertexIndex = indices[index];
  33260. if (vertexIndex < minVertexIndex)
  33261. minVertexIndex = vertexIndex;
  33262. if (vertexIndex > maxVertexIndex)
  33263. maxVertexIndex = vertexIndex;
  33264. }
  33265. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  33266. };
  33267. return SubMesh;
  33268. }(BaseSubMesh));
  33269. BABYLON.SubMesh = SubMesh;
  33270. })(BABYLON || (BABYLON = {}));
  33271. //# sourceMappingURL=babylon.subMesh.js.map
  33272. "use strict";
  33273. var __assign = (this && this.__assign) || Object.assign || function(t) {
  33274. for (var s, i = 1, n = arguments.length; i < n; i++) {
  33275. s = arguments[i];
  33276. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  33277. t[p] = s[p];
  33278. }
  33279. return t;
  33280. };
  33281. var BABYLON;
  33282. (function (BABYLON) {
  33283. /**
  33284. * Manages the defines for the Material
  33285. */
  33286. var MaterialDefines = /** @class */ (function () {
  33287. function MaterialDefines() {
  33288. this._isDirty = true;
  33289. this._areLightsDirty = true;
  33290. this._areAttributesDirty = true;
  33291. this._areTexturesDirty = true;
  33292. this._areFresnelDirty = true;
  33293. this._areMiscDirty = true;
  33294. this._areImageProcessingDirty = true;
  33295. this._normals = false;
  33296. this._uvs = false;
  33297. this._needNormals = false;
  33298. this._needUVs = false;
  33299. }
  33300. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  33301. /**
  33302. * Specifies if the material needs to be re-calculated
  33303. */
  33304. get: function () {
  33305. return this._isDirty;
  33306. },
  33307. enumerable: true,
  33308. configurable: true
  33309. });
  33310. /**
  33311. * Marks the material to indicate that it has been re-calculated
  33312. */
  33313. MaterialDefines.prototype.markAsProcessed = function () {
  33314. this._isDirty = false;
  33315. this._areAttributesDirty = false;
  33316. this._areTexturesDirty = false;
  33317. this._areFresnelDirty = false;
  33318. this._areLightsDirty = false;
  33319. this._areMiscDirty = false;
  33320. this._areImageProcessingDirty = false;
  33321. };
  33322. /**
  33323. * Marks the material to indicate that it needs to be re-calculated
  33324. */
  33325. MaterialDefines.prototype.markAsUnprocessed = function () {
  33326. this._isDirty = true;
  33327. };
  33328. /**
  33329. * Marks the material to indicate all of its defines need to be re-calculated
  33330. */
  33331. MaterialDefines.prototype.markAllAsDirty = function () {
  33332. this._areTexturesDirty = true;
  33333. this._areAttributesDirty = true;
  33334. this._areLightsDirty = true;
  33335. this._areFresnelDirty = true;
  33336. this._areMiscDirty = true;
  33337. this._areImageProcessingDirty = true;
  33338. this._isDirty = true;
  33339. };
  33340. /**
  33341. * Marks the material to indicate that image processing needs to be re-calculated
  33342. */
  33343. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  33344. this._areImageProcessingDirty = true;
  33345. this._isDirty = true;
  33346. };
  33347. /**
  33348. * Marks the material to indicate the lights need to be re-calculated
  33349. */
  33350. MaterialDefines.prototype.markAsLightDirty = function () {
  33351. this._areLightsDirty = true;
  33352. this._isDirty = true;
  33353. };
  33354. /**
  33355. * Marks the attribute state as changed
  33356. */
  33357. MaterialDefines.prototype.markAsAttributesDirty = function () {
  33358. this._areAttributesDirty = true;
  33359. this._isDirty = true;
  33360. };
  33361. /**
  33362. * Marks the texture state as changed
  33363. */
  33364. MaterialDefines.prototype.markAsTexturesDirty = function () {
  33365. this._areTexturesDirty = true;
  33366. this._isDirty = true;
  33367. };
  33368. /**
  33369. * Marks the fresnel state as changed
  33370. */
  33371. MaterialDefines.prototype.markAsFresnelDirty = function () {
  33372. this._areFresnelDirty = true;
  33373. this._isDirty = true;
  33374. };
  33375. /**
  33376. * Marks the misc state as changed
  33377. */
  33378. MaterialDefines.prototype.markAsMiscDirty = function () {
  33379. this._areMiscDirty = true;
  33380. this._isDirty = true;
  33381. };
  33382. /**
  33383. * Rebuilds the material defines
  33384. */
  33385. MaterialDefines.prototype.rebuild = function () {
  33386. if (this._keys) {
  33387. delete this._keys;
  33388. }
  33389. this._keys = [];
  33390. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  33391. var key = _a[_i];
  33392. if (key[0] === "_") {
  33393. continue;
  33394. }
  33395. this._keys.push(key);
  33396. }
  33397. };
  33398. /**
  33399. * Specifies if two material defines are equal
  33400. * @param other - A material define instance to compare to
  33401. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  33402. */
  33403. MaterialDefines.prototype.isEqual = function (other) {
  33404. if (this._keys.length !== other._keys.length) {
  33405. return false;
  33406. }
  33407. for (var index = 0; index < this._keys.length; index++) {
  33408. var prop = this._keys[index];
  33409. if (this[prop] !== other[prop]) {
  33410. return false;
  33411. }
  33412. }
  33413. return true;
  33414. };
  33415. /**
  33416. * Clones this instance's defines to another instance
  33417. * @param other - material defines to clone values to
  33418. */
  33419. MaterialDefines.prototype.cloneTo = function (other) {
  33420. if (this._keys.length !== other._keys.length) {
  33421. other._keys = this._keys.slice(0);
  33422. }
  33423. for (var index = 0; index < this._keys.length; index++) {
  33424. var prop = this._keys[index];
  33425. other[prop] = this[prop];
  33426. }
  33427. };
  33428. /**
  33429. * Resets the material define values
  33430. */
  33431. MaterialDefines.prototype.reset = function () {
  33432. for (var index = 0; index < this._keys.length; index++) {
  33433. var prop = this._keys[index];
  33434. var type = typeof this[prop];
  33435. switch (type) {
  33436. case "number":
  33437. this[prop] = 0;
  33438. break;
  33439. case "string":
  33440. this[prop] = "";
  33441. break;
  33442. default:
  33443. this[prop] = false;
  33444. break;
  33445. }
  33446. }
  33447. };
  33448. /**
  33449. * Converts the material define values to a string
  33450. * @returns - String of material define information
  33451. */
  33452. MaterialDefines.prototype.toString = function () {
  33453. var result = "";
  33454. for (var index = 0; index < this._keys.length; index++) {
  33455. var prop = this._keys[index];
  33456. var value = this[prop];
  33457. var type = typeof value;
  33458. switch (type) {
  33459. case "number":
  33460. case "string":
  33461. result += "#define " + prop + " " + value + "\n";
  33462. break;
  33463. default:
  33464. if (value) {
  33465. result += "#define " + prop + "\n";
  33466. }
  33467. break;
  33468. }
  33469. }
  33470. return result;
  33471. };
  33472. return MaterialDefines;
  33473. }());
  33474. BABYLON.MaterialDefines = MaterialDefines;
  33475. /**
  33476. * Base class for the main features of a material in Babylon.js
  33477. */
  33478. var Material = /** @class */ (function () {
  33479. /**
  33480. * Creates a material instance
  33481. * @param name defines the name of the material
  33482. * @param scene defines the scene to reference
  33483. * @param doNotAdd specifies if the material should be added to the scene
  33484. */
  33485. function Material(name, scene, doNotAdd) {
  33486. /**
  33487. * Specifies if the ready state should be checked on each call
  33488. */
  33489. this.checkReadyOnEveryCall = false;
  33490. /**
  33491. * Specifies if the ready state should be checked once
  33492. */
  33493. this.checkReadyOnlyOnce = false;
  33494. /**
  33495. * The state of the material
  33496. */
  33497. this.state = "";
  33498. /**
  33499. * The alpha value of the material
  33500. */
  33501. this._alpha = 1.0;
  33502. /**
  33503. * Specifies if back face culling is enabled
  33504. */
  33505. this._backFaceCulling = true;
  33506. /**
  33507. * Specifies if the material should be serialized
  33508. */
  33509. this.doNotSerialize = false;
  33510. /**
  33511. * Specifies if the effect should be stored on sub meshes
  33512. */
  33513. this.storeEffectOnSubMeshes = false;
  33514. /**
  33515. * An event triggered when the material is disposed
  33516. */
  33517. this.onDisposeObservable = new BABYLON.Observable();
  33518. /**
  33519. * An event triggered when the material is bound
  33520. */
  33521. this.onBindObservable = new BABYLON.Observable();
  33522. /**
  33523. * An event triggered when the material is unbound
  33524. */
  33525. this.onUnBindObservable = new BABYLON.Observable();
  33526. /**
  33527. * Stores the value of the alpha mode
  33528. */
  33529. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  33530. /**
  33531. * Stores the state of the need depth pre-pass value
  33532. */
  33533. this._needDepthPrePass = false;
  33534. /**
  33535. * Specifies if depth writing should be disabled
  33536. */
  33537. this.disableDepthWrite = false;
  33538. /**
  33539. * Specifies if depth writing should be forced
  33540. */
  33541. this.forceDepthWrite = false;
  33542. /**
  33543. * Specifies if there should be a separate pass for culling
  33544. */
  33545. this.separateCullingPass = false;
  33546. /**
  33547. * Stores the state specifing if fog should be enabled
  33548. */
  33549. this._fogEnabled = true;
  33550. /**
  33551. * Stores the size of points
  33552. */
  33553. this.pointSize = 1.0;
  33554. /**
  33555. * Stores the z offset value
  33556. */
  33557. this.zOffset = 0;
  33558. /**
  33559. * Specifies if the material was previously ready
  33560. */
  33561. this._wasPreviouslyReady = false;
  33562. /**
  33563. * Stores the fill mode state
  33564. */
  33565. this._fillMode = Material.TriangleFillMode;
  33566. this.name = name;
  33567. this.id = name || BABYLON.Tools.RandomId();
  33568. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  33569. if (this._scene.useRightHandedSystem) {
  33570. this.sideOrientation = Material.ClockWiseSideOrientation;
  33571. }
  33572. else {
  33573. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  33574. }
  33575. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  33576. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  33577. if (!doNotAdd) {
  33578. this._scene.materials.push(this);
  33579. }
  33580. }
  33581. Object.defineProperty(Material, "TriangleFillMode", {
  33582. /**
  33583. * Returns the triangle fill mode
  33584. */
  33585. get: function () {
  33586. return Material._TriangleFillMode;
  33587. },
  33588. enumerable: true,
  33589. configurable: true
  33590. });
  33591. Object.defineProperty(Material, "WireFrameFillMode", {
  33592. /**
  33593. * Returns the wireframe mode
  33594. */
  33595. get: function () {
  33596. return Material._WireFrameFillMode;
  33597. },
  33598. enumerable: true,
  33599. configurable: true
  33600. });
  33601. Object.defineProperty(Material, "PointFillMode", {
  33602. /**
  33603. * Returns the point fill mode
  33604. */
  33605. get: function () {
  33606. return Material._PointFillMode;
  33607. },
  33608. enumerable: true,
  33609. configurable: true
  33610. });
  33611. Object.defineProperty(Material, "PointListDrawMode", {
  33612. /**
  33613. * Returns the point list draw mode
  33614. */
  33615. get: function () {
  33616. return Material._PointListDrawMode;
  33617. },
  33618. enumerable: true,
  33619. configurable: true
  33620. });
  33621. Object.defineProperty(Material, "LineListDrawMode", {
  33622. /**
  33623. * Returns the line list draw mode
  33624. */
  33625. get: function () {
  33626. return Material._LineListDrawMode;
  33627. },
  33628. enumerable: true,
  33629. configurable: true
  33630. });
  33631. Object.defineProperty(Material, "LineLoopDrawMode", {
  33632. /**
  33633. * Returns the line loop draw mode
  33634. */
  33635. get: function () {
  33636. return Material._LineLoopDrawMode;
  33637. },
  33638. enumerable: true,
  33639. configurable: true
  33640. });
  33641. Object.defineProperty(Material, "LineStripDrawMode", {
  33642. /**
  33643. * Returns the line strip draw mode
  33644. */
  33645. get: function () {
  33646. return Material._LineStripDrawMode;
  33647. },
  33648. enumerable: true,
  33649. configurable: true
  33650. });
  33651. Object.defineProperty(Material, "TriangleStripDrawMode", {
  33652. /**
  33653. * Returns the triangle strip draw mode
  33654. */
  33655. get: function () {
  33656. return Material._TriangleStripDrawMode;
  33657. },
  33658. enumerable: true,
  33659. configurable: true
  33660. });
  33661. Object.defineProperty(Material, "TriangleFanDrawMode", {
  33662. /**
  33663. * Returns the triangle fan draw mode
  33664. */
  33665. get: function () {
  33666. return Material._TriangleFanDrawMode;
  33667. },
  33668. enumerable: true,
  33669. configurable: true
  33670. });
  33671. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  33672. /**
  33673. * Returns the clock-wise side orientation
  33674. */
  33675. get: function () {
  33676. return Material._ClockWiseSideOrientation;
  33677. },
  33678. enumerable: true,
  33679. configurable: true
  33680. });
  33681. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  33682. /**
  33683. * Returns the counter clock-wise side orientation
  33684. */
  33685. get: function () {
  33686. return Material._CounterClockWiseSideOrientation;
  33687. },
  33688. enumerable: true,
  33689. configurable: true
  33690. });
  33691. Object.defineProperty(Material, "TextureDirtyFlag", {
  33692. /**
  33693. * Returns the dirty texture flag value
  33694. */
  33695. get: function () {
  33696. return Material._TextureDirtyFlag;
  33697. },
  33698. enumerable: true,
  33699. configurable: true
  33700. });
  33701. Object.defineProperty(Material, "LightDirtyFlag", {
  33702. /**
  33703. * Returns the dirty light flag value
  33704. */
  33705. get: function () {
  33706. return Material._LightDirtyFlag;
  33707. },
  33708. enumerable: true,
  33709. configurable: true
  33710. });
  33711. Object.defineProperty(Material, "FresnelDirtyFlag", {
  33712. /**
  33713. * Returns the dirty fresnel flag value
  33714. */
  33715. get: function () {
  33716. return Material._FresnelDirtyFlag;
  33717. },
  33718. enumerable: true,
  33719. configurable: true
  33720. });
  33721. Object.defineProperty(Material, "AttributesDirtyFlag", {
  33722. /**
  33723. * Returns the dirty attributes flag value
  33724. */
  33725. get: function () {
  33726. return Material._AttributesDirtyFlag;
  33727. },
  33728. enumerable: true,
  33729. configurable: true
  33730. });
  33731. Object.defineProperty(Material, "MiscDirtyFlag", {
  33732. /**
  33733. * Returns the dirty misc flag value
  33734. */
  33735. get: function () {
  33736. return Material._MiscDirtyFlag;
  33737. },
  33738. enumerable: true,
  33739. configurable: true
  33740. });
  33741. Object.defineProperty(Material.prototype, "alpha", {
  33742. /**
  33743. * Gets the alpha value of the material
  33744. */
  33745. get: function () {
  33746. return this._alpha;
  33747. },
  33748. /**
  33749. * Sets the alpha value of the material
  33750. */
  33751. set: function (value) {
  33752. if (this._alpha === value) {
  33753. return;
  33754. }
  33755. this._alpha = value;
  33756. this.markAsDirty(Material.MiscDirtyFlag);
  33757. },
  33758. enumerable: true,
  33759. configurable: true
  33760. });
  33761. Object.defineProperty(Material.prototype, "backFaceCulling", {
  33762. /**
  33763. * Gets the back-face culling state
  33764. */
  33765. get: function () {
  33766. return this._backFaceCulling;
  33767. },
  33768. /**
  33769. * Sets the back-face culling state
  33770. */
  33771. set: function (value) {
  33772. if (this._backFaceCulling === value) {
  33773. return;
  33774. }
  33775. this._backFaceCulling = value;
  33776. this.markAsDirty(Material.TextureDirtyFlag);
  33777. },
  33778. enumerable: true,
  33779. configurable: true
  33780. });
  33781. Object.defineProperty(Material.prototype, "onDispose", {
  33782. /**
  33783. * Called during a dispose event
  33784. */
  33785. set: function (callback) {
  33786. if (this._onDisposeObserver) {
  33787. this.onDisposeObservable.remove(this._onDisposeObserver);
  33788. }
  33789. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  33790. },
  33791. enumerable: true,
  33792. configurable: true
  33793. });
  33794. Object.defineProperty(Material.prototype, "onBind", {
  33795. /**
  33796. * Called during a bind event
  33797. */
  33798. set: function (callback) {
  33799. if (this._onBindObserver) {
  33800. this.onBindObservable.remove(this._onBindObserver);
  33801. }
  33802. this._onBindObserver = this.onBindObservable.add(callback);
  33803. },
  33804. enumerable: true,
  33805. configurable: true
  33806. });
  33807. Object.defineProperty(Material.prototype, "alphaMode", {
  33808. /**
  33809. * Gets the value of the alpha mode
  33810. */
  33811. get: function () {
  33812. return this._alphaMode;
  33813. },
  33814. /**
  33815. * Sets the value of the alpha mode.
  33816. *
  33817. * | Value | Type | Description |
  33818. * | --- | --- | --- |
  33819. * | 0 | ALPHA_DISABLE | |
  33820. * | 1 | ALPHA_ADD | |
  33821. * | 2 | ALPHA_COMBINE | |
  33822. * | 3 | ALPHA_SUBTRACT | |
  33823. * | 4 | ALPHA_MULTIPLY | |
  33824. * | 5 | ALPHA_MAXIMIZED | |
  33825. * | 6 | ALPHA_ONEONE | |
  33826. * | 7 | ALPHA_PREMULTIPLIED | |
  33827. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  33828. * | 9 | ALPHA_INTERPOLATE | |
  33829. * | 10 | ALPHA_SCREENMODE | |
  33830. *
  33831. */
  33832. set: function (value) {
  33833. if (this._alphaMode === value) {
  33834. return;
  33835. }
  33836. this._alphaMode = value;
  33837. this.markAsDirty(Material.TextureDirtyFlag);
  33838. },
  33839. enumerable: true,
  33840. configurable: true
  33841. });
  33842. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  33843. /**
  33844. * Gets the depth pre-pass value
  33845. */
  33846. get: function () {
  33847. return this._needDepthPrePass;
  33848. },
  33849. /**
  33850. * Sets the need depth pre-pass value
  33851. */
  33852. set: function (value) {
  33853. if (this._needDepthPrePass === value) {
  33854. return;
  33855. }
  33856. this._needDepthPrePass = value;
  33857. if (this._needDepthPrePass) {
  33858. this.checkReadyOnEveryCall = true;
  33859. }
  33860. },
  33861. enumerable: true,
  33862. configurable: true
  33863. });
  33864. Object.defineProperty(Material.prototype, "fogEnabled", {
  33865. /**
  33866. * Gets the value of the fog enabled state
  33867. */
  33868. get: function () {
  33869. return this._fogEnabled;
  33870. },
  33871. /**
  33872. * Sets the state for enabling fog
  33873. */
  33874. set: function (value) {
  33875. if (this._fogEnabled === value) {
  33876. return;
  33877. }
  33878. this._fogEnabled = value;
  33879. this.markAsDirty(Material.MiscDirtyFlag);
  33880. },
  33881. enumerable: true,
  33882. configurable: true
  33883. });
  33884. Object.defineProperty(Material.prototype, "wireframe", {
  33885. /**
  33886. * Gets a value specifying if wireframe mode is enabled
  33887. */
  33888. get: function () {
  33889. switch (this._fillMode) {
  33890. case Material.WireFrameFillMode:
  33891. case Material.LineListDrawMode:
  33892. case Material.LineLoopDrawMode:
  33893. case Material.LineStripDrawMode:
  33894. return true;
  33895. }
  33896. return this._scene.forceWireframe;
  33897. },
  33898. /**
  33899. * Sets the state of wireframe mode
  33900. */
  33901. set: function (value) {
  33902. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  33903. },
  33904. enumerable: true,
  33905. configurable: true
  33906. });
  33907. Object.defineProperty(Material.prototype, "pointsCloud", {
  33908. /**
  33909. * Gets the value specifying if point clouds are enabled
  33910. */
  33911. get: function () {
  33912. switch (this._fillMode) {
  33913. case Material.PointFillMode:
  33914. case Material.PointListDrawMode:
  33915. return true;
  33916. }
  33917. return this._scene.forcePointsCloud;
  33918. },
  33919. /**
  33920. * Sets the state of point cloud mode
  33921. */
  33922. set: function (value) {
  33923. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  33924. },
  33925. enumerable: true,
  33926. configurable: true
  33927. });
  33928. Object.defineProperty(Material.prototype, "fillMode", {
  33929. /**
  33930. * Gets the material fill mode
  33931. */
  33932. get: function () {
  33933. return this._fillMode;
  33934. },
  33935. /**
  33936. * Sets the material fill mode
  33937. */
  33938. set: function (value) {
  33939. if (this._fillMode === value) {
  33940. return;
  33941. }
  33942. this._fillMode = value;
  33943. this.markAsDirty(Material.MiscDirtyFlag);
  33944. },
  33945. enumerable: true,
  33946. configurable: true
  33947. });
  33948. /**
  33949. * Returns a string representation of the current material
  33950. * @param fullDetails defines a boolean indicating which levels of logging is desired
  33951. * @returns a string with material information
  33952. */
  33953. Material.prototype.toString = function (fullDetails) {
  33954. var ret = "Name: " + this.name;
  33955. if (fullDetails) {
  33956. }
  33957. return ret;
  33958. };
  33959. /**
  33960. * Gets the class name of the material
  33961. * @returns a string with the class name of the material
  33962. */
  33963. Material.prototype.getClassName = function () {
  33964. return "Material";
  33965. };
  33966. Object.defineProperty(Material.prototype, "isFrozen", {
  33967. /**
  33968. * Specifies if updates for the material been locked
  33969. */
  33970. get: function () {
  33971. return this.checkReadyOnlyOnce;
  33972. },
  33973. enumerable: true,
  33974. configurable: true
  33975. });
  33976. /**
  33977. * Locks updates for the material
  33978. */
  33979. Material.prototype.freeze = function () {
  33980. this.checkReadyOnlyOnce = true;
  33981. };
  33982. /**
  33983. * Unlocks updates for the material
  33984. */
  33985. Material.prototype.unfreeze = function () {
  33986. this.checkReadyOnlyOnce = false;
  33987. };
  33988. /**
  33989. * Specifies if the material is ready to be used
  33990. * @param mesh defines the mesh to check
  33991. * @param useInstances specifies if instances should be used
  33992. * @returns a boolean indicating if the material is ready to be used
  33993. */
  33994. Material.prototype.isReady = function (mesh, useInstances) {
  33995. return true;
  33996. };
  33997. /**
  33998. * Specifies that the submesh is ready to be used
  33999. * @param mesh defines the mesh to check
  34000. * @param subMesh defines which submesh to check
  34001. * @param useInstances specifies that instances should be used
  34002. * @returns a boolean indicating that the submesh is ready or not
  34003. */
  34004. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34005. return false;
  34006. };
  34007. /**
  34008. * Returns the material effect
  34009. * @returns the effect associated with the material
  34010. */
  34011. Material.prototype.getEffect = function () {
  34012. return this._effect;
  34013. };
  34014. /**
  34015. * Returns the current scene
  34016. * @returns a Scene
  34017. */
  34018. Material.prototype.getScene = function () {
  34019. return this._scene;
  34020. };
  34021. /**
  34022. * Specifies if the material will require alpha blending
  34023. * @returns a boolean specifying if alpha blending is needed
  34024. */
  34025. Material.prototype.needAlphaBlending = function () {
  34026. return (this.alpha < 1.0);
  34027. };
  34028. /**
  34029. * Specifies if the mesh will require alpha blending
  34030. * @param mesh defines the mesh to check
  34031. * @returns a boolean specifying if alpha blending is needed for the mesh
  34032. */
  34033. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  34034. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  34035. };
  34036. /**
  34037. * Specifies if this material should be rendered in alpha test mode
  34038. * @returns a boolean specifying if an alpha test is needed.
  34039. */
  34040. Material.prototype.needAlphaTesting = function () {
  34041. return false;
  34042. };
  34043. /**
  34044. * Gets the texture used for the alpha test
  34045. * @returns the texture to use for alpha testing
  34046. */
  34047. Material.prototype.getAlphaTestTexture = function () {
  34048. return null;
  34049. };
  34050. /**
  34051. * Marks the material to indicate that it needs to be re-calculated
  34052. */
  34053. Material.prototype.markDirty = function () {
  34054. this._wasPreviouslyReady = false;
  34055. };
  34056. /** @ignore */
  34057. Material.prototype._preBind = function (effect, overrideOrientation) {
  34058. if (overrideOrientation === void 0) { overrideOrientation = null; }
  34059. var engine = this._scene.getEngine();
  34060. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  34061. var reverse = orientation === Material.ClockWiseSideOrientation;
  34062. engine.enableEffect(effect ? effect : this._effect);
  34063. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  34064. return reverse;
  34065. };
  34066. /**
  34067. * Binds the material to the mesh
  34068. * @param world defines the world transformation matrix
  34069. * @param mesh defines the mesh to bind the material to
  34070. */
  34071. Material.prototype.bind = function (world, mesh) {
  34072. };
  34073. /**
  34074. * Binds the submesh to the material
  34075. * @param world defines the world transformation matrix
  34076. * @param mesh defines the mesh containing the submesh
  34077. * @param subMesh defines the submesh to bind the material to
  34078. */
  34079. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  34080. };
  34081. /**
  34082. * Binds the world matrix to the material
  34083. * @param world defines the world transformation matrix
  34084. */
  34085. Material.prototype.bindOnlyWorldMatrix = function (world) {
  34086. };
  34087. /**
  34088. * Binds the scene's uniform buffer to the effect.
  34089. * @param effect defines the effect to bind to the scene uniform buffer
  34090. * @param sceneUbo defines the uniform buffer storing scene data
  34091. */
  34092. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  34093. sceneUbo.bindToEffect(effect, "Scene");
  34094. };
  34095. /**
  34096. * Binds the view matrix to the effect
  34097. * @param effect defines the effect to bind the view matrix to
  34098. */
  34099. Material.prototype.bindView = function (effect) {
  34100. if (!this._useUBO) {
  34101. effect.setMatrix("view", this.getScene().getViewMatrix());
  34102. }
  34103. else {
  34104. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  34105. }
  34106. };
  34107. /**
  34108. * Binds the view projection matrix to the effect
  34109. * @param effect defines the effect to bind the view projection matrix to
  34110. */
  34111. Material.prototype.bindViewProjection = function (effect) {
  34112. if (!this._useUBO) {
  34113. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  34114. }
  34115. else {
  34116. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  34117. }
  34118. };
  34119. /**
  34120. * Specifies if material alpha testing should be turned on for the mesh
  34121. * @param mesh defines the mesh to check
  34122. */
  34123. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  34124. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  34125. };
  34126. /**
  34127. * Processes to execute after binding the material to a mesh
  34128. * @param mesh defines the rendered mesh
  34129. */
  34130. Material.prototype._afterBind = function (mesh) {
  34131. this._scene._cachedMaterial = this;
  34132. if (mesh) {
  34133. this._scene._cachedVisibility = mesh.visibility;
  34134. }
  34135. else {
  34136. this._scene._cachedVisibility = 1;
  34137. }
  34138. if (mesh) {
  34139. this.onBindObservable.notifyObservers(mesh);
  34140. }
  34141. if (this.disableDepthWrite) {
  34142. var engine = this._scene.getEngine();
  34143. this._cachedDepthWriteState = engine.getDepthWrite();
  34144. engine.setDepthWrite(false);
  34145. }
  34146. };
  34147. /**
  34148. * Unbinds the material from the mesh
  34149. */
  34150. Material.prototype.unbind = function () {
  34151. this.onUnBindObservable.notifyObservers(this);
  34152. if (this.disableDepthWrite) {
  34153. var engine = this._scene.getEngine();
  34154. engine.setDepthWrite(this._cachedDepthWriteState);
  34155. }
  34156. };
  34157. /**
  34158. * Gets the active textures from the material
  34159. * @returns an array of textures
  34160. */
  34161. Material.prototype.getActiveTextures = function () {
  34162. return [];
  34163. };
  34164. /**
  34165. * Specifies if the material uses a texture
  34166. * @param texture defines the texture to check against the material
  34167. * @returns a boolean specifying if the material uses the texture
  34168. */
  34169. Material.prototype.hasTexture = function (texture) {
  34170. return false;
  34171. };
  34172. /**
  34173. * Makes a duplicate of the material, and gives it a new name
  34174. * @param name defines the new name for the duplicated material
  34175. * @returns the cloned material
  34176. */
  34177. Material.prototype.clone = function (name) {
  34178. return null;
  34179. };
  34180. /**
  34181. * Gets the meshes bound to the material
  34182. * @returns an array of meshes bound to the material
  34183. */
  34184. Material.prototype.getBindedMeshes = function () {
  34185. var result = new Array();
  34186. for (var index = 0; index < this._scene.meshes.length; index++) {
  34187. var mesh = this._scene.meshes[index];
  34188. if (mesh.material === this) {
  34189. result.push(mesh);
  34190. }
  34191. }
  34192. return result;
  34193. };
  34194. /**
  34195. * Force shader compilation
  34196. * @param mesh defines the mesh associated with this material
  34197. * @param onCompiled defines a function to execute once the material is compiled
  34198. * @param options defines the options to configure the compilation
  34199. */
  34200. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  34201. var _this = this;
  34202. var localOptions = __assign({ clipPlane: false }, options);
  34203. var subMesh = new BABYLON.BaseSubMesh();
  34204. var scene = this.getScene();
  34205. var checkReady = function () {
  34206. if (!_this._scene || !_this._scene.getEngine()) {
  34207. return;
  34208. }
  34209. if (subMesh._materialDefines) {
  34210. subMesh._materialDefines._renderId = -1;
  34211. }
  34212. var clipPlaneState = scene.clipPlane;
  34213. if (localOptions.clipPlane) {
  34214. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  34215. }
  34216. if (_this.storeEffectOnSubMeshes) {
  34217. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  34218. if (onCompiled) {
  34219. onCompiled(_this);
  34220. }
  34221. }
  34222. else {
  34223. setTimeout(checkReady, 16);
  34224. }
  34225. }
  34226. else {
  34227. if (_this.isReady(mesh)) {
  34228. if (onCompiled) {
  34229. onCompiled(_this);
  34230. }
  34231. }
  34232. else {
  34233. setTimeout(checkReady, 16);
  34234. }
  34235. }
  34236. if (localOptions.clipPlane) {
  34237. scene.clipPlane = clipPlaneState;
  34238. }
  34239. };
  34240. checkReady();
  34241. };
  34242. /**
  34243. * Force shader compilation
  34244. * @param mesh defines the mesh that will use this material
  34245. * @param options defines additional options for compiling the shaders
  34246. * @returns a promise that resolves when the compilation completes
  34247. */
  34248. Material.prototype.forceCompilationAsync = function (mesh, options) {
  34249. var _this = this;
  34250. return new Promise(function (resolve) {
  34251. _this.forceCompilation(mesh, function () {
  34252. resolve();
  34253. }, options);
  34254. });
  34255. };
  34256. /**
  34257. * Marks a define in the material to indicate that it needs to be re-computed
  34258. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  34259. */
  34260. Material.prototype.markAsDirty = function (flag) {
  34261. if (flag & Material.TextureDirtyFlag) {
  34262. this._markAllSubMeshesAsTexturesDirty();
  34263. }
  34264. if (flag & Material.LightDirtyFlag) {
  34265. this._markAllSubMeshesAsLightsDirty();
  34266. }
  34267. if (flag & Material.FresnelDirtyFlag) {
  34268. this._markAllSubMeshesAsFresnelDirty();
  34269. }
  34270. if (flag & Material.AttributesDirtyFlag) {
  34271. this._markAllSubMeshesAsAttributesDirty();
  34272. }
  34273. if (flag & Material.MiscDirtyFlag) {
  34274. this._markAllSubMeshesAsMiscDirty();
  34275. }
  34276. this.getScene().resetCachedMaterial();
  34277. };
  34278. /**
  34279. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  34280. * @param func defines a function which checks material defines against the submeshes
  34281. */
  34282. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  34283. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  34284. var mesh = _a[_i];
  34285. if (!mesh.subMeshes) {
  34286. continue;
  34287. }
  34288. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  34289. var subMesh = _c[_b];
  34290. if (subMesh.getMaterial() !== this) {
  34291. continue;
  34292. }
  34293. if (!subMesh._materialDefines) {
  34294. continue;
  34295. }
  34296. func(subMesh._materialDefines);
  34297. }
  34298. }
  34299. };
  34300. /**
  34301. * Indicates that image processing needs to be re-calculated for all submeshes
  34302. */
  34303. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  34304. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  34305. };
  34306. /**
  34307. * Indicates that textures need to be re-calculated for all submeshes
  34308. */
  34309. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  34310. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  34311. };
  34312. /**
  34313. * Indicates that fresnel needs to be re-calculated for all submeshes
  34314. */
  34315. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  34316. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  34317. };
  34318. /**
  34319. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  34320. */
  34321. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  34322. this._markAllSubMeshesAsDirty(function (defines) {
  34323. defines.markAsFresnelDirty();
  34324. defines.markAsMiscDirty();
  34325. });
  34326. };
  34327. /**
  34328. * Indicates that lights need to be re-calculated for all submeshes
  34329. */
  34330. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  34331. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  34332. };
  34333. /**
  34334. * Indicates that attributes need to be re-calculated for all submeshes
  34335. */
  34336. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  34337. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  34338. };
  34339. /**
  34340. * Indicates that misc needs to be re-calculated for all submeshes
  34341. */
  34342. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  34343. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  34344. };
  34345. /**
  34346. * Indicates that textures and misc need to be re-calculated for all submeshes
  34347. */
  34348. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  34349. this._markAllSubMeshesAsDirty(function (defines) {
  34350. defines.markAsTexturesDirty();
  34351. defines.markAsMiscDirty();
  34352. });
  34353. };
  34354. /**
  34355. * Disposes the material
  34356. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  34357. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  34358. */
  34359. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  34360. // Animations
  34361. this.getScene().stopAnimation(this);
  34362. this.getScene().freeProcessedMaterials();
  34363. // Remove from scene
  34364. var index = this._scene.materials.indexOf(this);
  34365. if (index >= 0) {
  34366. this._scene.materials.splice(index, 1);
  34367. }
  34368. // Remove from meshes
  34369. for (index = 0; index < this._scene.meshes.length; index++) {
  34370. var mesh = this._scene.meshes[index];
  34371. if (mesh.material === this) {
  34372. mesh.material = null;
  34373. if (mesh.geometry) {
  34374. var geometry = (mesh.geometry);
  34375. if (this.storeEffectOnSubMeshes) {
  34376. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  34377. var subMesh = _a[_i];
  34378. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  34379. if (forceDisposeEffect && subMesh._materialEffect) {
  34380. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  34381. }
  34382. }
  34383. }
  34384. else {
  34385. geometry._releaseVertexArrayObject(this._effect);
  34386. }
  34387. }
  34388. }
  34389. }
  34390. this._uniformBuffer.dispose();
  34391. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  34392. if (forceDisposeEffect && this._effect) {
  34393. if (!this.storeEffectOnSubMeshes) {
  34394. this._scene.getEngine()._releaseEffect(this._effect);
  34395. }
  34396. this._effect = null;
  34397. }
  34398. // Callback
  34399. this.onDisposeObservable.notifyObservers(this);
  34400. this.onDisposeObservable.clear();
  34401. this.onBindObservable.clear();
  34402. this.onUnBindObservable.clear();
  34403. };
  34404. /**
  34405. * Serializes this material
  34406. * @returns the serialized material object
  34407. */
  34408. Material.prototype.serialize = function () {
  34409. return BABYLON.SerializationHelper.Serialize(this);
  34410. };
  34411. /**
  34412. * Creates a MultiMaterial from parsed MultiMaterial data.
  34413. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  34414. * @param scene defines the hosting scene
  34415. * @returns a new MultiMaterial
  34416. */
  34417. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  34418. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  34419. multiMaterial.id = parsedMultiMaterial.id;
  34420. if (BABYLON.Tags) {
  34421. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  34422. }
  34423. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  34424. var subMatId = parsedMultiMaterial.materials[matIndex];
  34425. if (subMatId) {
  34426. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  34427. }
  34428. else {
  34429. multiMaterial.subMaterials.push(null);
  34430. }
  34431. }
  34432. return multiMaterial;
  34433. };
  34434. /**
  34435. * Creates a material from parsed material data
  34436. * @param parsedMaterial defines parsed material data
  34437. * @param scene defines the hosting scene
  34438. * @param rootUrl defines the root URL to use to load textures
  34439. * @returns a new material
  34440. */
  34441. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  34442. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  34443. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  34444. }
  34445. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  34446. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  34447. if (!BABYLON.LegacyPBRMaterial) {
  34448. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  34449. return;
  34450. }
  34451. }
  34452. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  34453. return materialType.Parse(parsedMaterial, scene, rootUrl);
  34454. ;
  34455. };
  34456. // Triangle views
  34457. Material._TriangleFillMode = 0;
  34458. Material._WireFrameFillMode = 1;
  34459. Material._PointFillMode = 2;
  34460. // Draw modes
  34461. Material._PointListDrawMode = 3;
  34462. Material._LineListDrawMode = 4;
  34463. Material._LineLoopDrawMode = 5;
  34464. Material._LineStripDrawMode = 6;
  34465. Material._TriangleStripDrawMode = 7;
  34466. Material._TriangleFanDrawMode = 8;
  34467. /**
  34468. * Stores the clock-wise side orientation
  34469. */
  34470. Material._ClockWiseSideOrientation = 0;
  34471. /**
  34472. * Stores the counter clock-wise side orientation
  34473. */
  34474. Material._CounterClockWiseSideOrientation = 1;
  34475. /**
  34476. * The dirty texture flag value
  34477. */
  34478. Material._TextureDirtyFlag = 1;
  34479. /**
  34480. * The dirty light flag value
  34481. */
  34482. Material._LightDirtyFlag = 2;
  34483. /**
  34484. * The dirty fresnel flag value
  34485. */
  34486. Material._FresnelDirtyFlag = 4;
  34487. /**
  34488. * The dirty attribute flag value
  34489. */
  34490. Material._AttributesDirtyFlag = 8;
  34491. /**
  34492. * The dirty misc flag value
  34493. */
  34494. Material._MiscDirtyFlag = 16;
  34495. __decorate([
  34496. BABYLON.serialize()
  34497. ], Material.prototype, "id", void 0);
  34498. __decorate([
  34499. BABYLON.serialize()
  34500. ], Material.prototype, "name", void 0);
  34501. __decorate([
  34502. BABYLON.serialize()
  34503. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  34504. __decorate([
  34505. BABYLON.serialize()
  34506. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  34507. __decorate([
  34508. BABYLON.serialize()
  34509. ], Material.prototype, "state", void 0);
  34510. __decorate([
  34511. BABYLON.serialize("alpha")
  34512. ], Material.prototype, "_alpha", void 0);
  34513. __decorate([
  34514. BABYLON.serialize("backFaceCulling")
  34515. ], Material.prototype, "_backFaceCulling", void 0);
  34516. __decorate([
  34517. BABYLON.serialize()
  34518. ], Material.prototype, "sideOrientation", void 0);
  34519. __decorate([
  34520. BABYLON.serialize("alphaMode")
  34521. ], Material.prototype, "_alphaMode", void 0);
  34522. __decorate([
  34523. BABYLON.serialize()
  34524. ], Material.prototype, "_needDepthPrePass", void 0);
  34525. __decorate([
  34526. BABYLON.serialize()
  34527. ], Material.prototype, "disableDepthWrite", void 0);
  34528. __decorate([
  34529. BABYLON.serialize()
  34530. ], Material.prototype, "forceDepthWrite", void 0);
  34531. __decorate([
  34532. BABYLON.serialize()
  34533. ], Material.prototype, "separateCullingPass", void 0);
  34534. __decorate([
  34535. BABYLON.serialize("fogEnabled")
  34536. ], Material.prototype, "_fogEnabled", void 0);
  34537. __decorate([
  34538. BABYLON.serialize()
  34539. ], Material.prototype, "pointSize", void 0);
  34540. __decorate([
  34541. BABYLON.serialize()
  34542. ], Material.prototype, "zOffset", void 0);
  34543. __decorate([
  34544. BABYLON.serialize()
  34545. ], Material.prototype, "wireframe", null);
  34546. __decorate([
  34547. BABYLON.serialize()
  34548. ], Material.prototype, "pointsCloud", null);
  34549. __decorate([
  34550. BABYLON.serialize()
  34551. ], Material.prototype, "fillMode", null);
  34552. return Material;
  34553. }());
  34554. BABYLON.Material = Material;
  34555. })(BABYLON || (BABYLON = {}));
  34556. //# sourceMappingURL=babylon.material.js.map
  34557. "use strict";
  34558. var BABYLON;
  34559. (function (BABYLON) {
  34560. var UniformBuffer = /** @class */ (function () {
  34561. /**
  34562. * Uniform buffer objects.
  34563. *
  34564. * Handles blocks of uniform on the GPU.
  34565. *
  34566. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  34567. *
  34568. * For more information, please refer to :
  34569. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  34570. */
  34571. function UniformBuffer(engine, data, dynamic) {
  34572. this._engine = engine;
  34573. this._noUBO = !engine.supportsUniformBuffers;
  34574. this._dynamic = dynamic;
  34575. this._data = data || [];
  34576. this._uniformLocations = {};
  34577. this._uniformSizes = {};
  34578. this._uniformLocationPointer = 0;
  34579. this._needSync = false;
  34580. if (this._noUBO) {
  34581. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  34582. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  34583. this.updateFloat = this._updateFloatForEffect;
  34584. this.updateFloat2 = this._updateFloat2ForEffect;
  34585. this.updateFloat3 = this._updateFloat3ForEffect;
  34586. this.updateFloat4 = this._updateFloat4ForEffect;
  34587. this.updateMatrix = this._updateMatrixForEffect;
  34588. this.updateVector3 = this._updateVector3ForEffect;
  34589. this.updateVector4 = this._updateVector4ForEffect;
  34590. this.updateColor3 = this._updateColor3ForEffect;
  34591. this.updateColor4 = this._updateColor4ForEffect;
  34592. }
  34593. else {
  34594. this._engine._uniformBuffers.push(this);
  34595. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  34596. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  34597. this.updateFloat = this._updateFloatForUniform;
  34598. this.updateFloat2 = this._updateFloat2ForUniform;
  34599. this.updateFloat3 = this._updateFloat3ForUniform;
  34600. this.updateFloat4 = this._updateFloat4ForUniform;
  34601. this.updateMatrix = this._updateMatrixForUniform;
  34602. this.updateVector3 = this._updateVector3ForUniform;
  34603. this.updateVector4 = this._updateVector4ForUniform;
  34604. this.updateColor3 = this._updateColor3ForUniform;
  34605. this.updateColor4 = this._updateColor4ForUniform;
  34606. }
  34607. }
  34608. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  34609. // Properties
  34610. /**
  34611. * Indicates if the buffer is using the WebGL2 UBO implementation,
  34612. * or just falling back on setUniformXXX calls.
  34613. */
  34614. get: function () {
  34615. return !this._noUBO;
  34616. },
  34617. enumerable: true,
  34618. configurable: true
  34619. });
  34620. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  34621. /**
  34622. * Indicates if the WebGL underlying uniform buffer is in sync
  34623. * with the javascript cache data.
  34624. */
  34625. get: function () {
  34626. return !this._needSync;
  34627. },
  34628. enumerable: true,
  34629. configurable: true
  34630. });
  34631. /**
  34632. * Indicates if the WebGL underlying uniform buffer is dynamic.
  34633. * Also, a dynamic UniformBuffer will disable cache verification and always
  34634. * update the underlying WebGL uniform buffer to the GPU.
  34635. */
  34636. UniformBuffer.prototype.isDynamic = function () {
  34637. return this._dynamic !== undefined;
  34638. };
  34639. /**
  34640. * The data cache on JS side.
  34641. */
  34642. UniformBuffer.prototype.getData = function () {
  34643. return this._bufferData;
  34644. };
  34645. /**
  34646. * The underlying WebGL Uniform buffer.
  34647. */
  34648. UniformBuffer.prototype.getBuffer = function () {
  34649. return this._buffer;
  34650. };
  34651. /**
  34652. * std140 layout specifies how to align data within an UBO structure.
  34653. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  34654. * for specs.
  34655. */
  34656. UniformBuffer.prototype._fillAlignment = function (size) {
  34657. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  34658. // and 4x4 matrices
  34659. // TODO : change if other types are used
  34660. var alignment;
  34661. if (size <= 2) {
  34662. alignment = size;
  34663. }
  34664. else {
  34665. alignment = 4;
  34666. }
  34667. if ((this._uniformLocationPointer % alignment) !== 0) {
  34668. var oldPointer = this._uniformLocationPointer;
  34669. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  34670. var diff = this._uniformLocationPointer - oldPointer;
  34671. for (var i = 0; i < diff; i++) {
  34672. this._data.push(0);
  34673. }
  34674. }
  34675. };
  34676. /**
  34677. * Adds an uniform in the buffer.
  34678. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  34679. * for the layout to be correct !
  34680. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  34681. * @param {number|number[]} size Data size, or data directly.
  34682. */
  34683. UniformBuffer.prototype.addUniform = function (name, size) {
  34684. if (this._noUBO) {
  34685. return;
  34686. }
  34687. if (this._uniformLocations[name] !== undefined) {
  34688. // Already existing uniform
  34689. return;
  34690. }
  34691. // This function must be called in the order of the shader layout !
  34692. // size can be the size of the uniform, or data directly
  34693. var data;
  34694. if (size instanceof Array) {
  34695. data = size;
  34696. size = data.length;
  34697. }
  34698. else {
  34699. size = size;
  34700. data = [];
  34701. // Fill with zeros
  34702. for (var i = 0; i < size; i++) {
  34703. data.push(0);
  34704. }
  34705. }
  34706. this._fillAlignment(size);
  34707. this._uniformSizes[name] = size;
  34708. this._uniformLocations[name] = this._uniformLocationPointer;
  34709. this._uniformLocationPointer += size;
  34710. for (var i = 0; i < size; i++) {
  34711. this._data.push(data[i]);
  34712. }
  34713. this._needSync = true;
  34714. };
  34715. /**
  34716. * Wrapper for addUniform.
  34717. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  34718. * @param {Matrix} mat A 4x4 matrix.
  34719. */
  34720. UniformBuffer.prototype.addMatrix = function (name, mat) {
  34721. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  34722. };
  34723. /**
  34724. * Wrapper for addUniform.
  34725. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  34726. * @param {number} x
  34727. * @param {number} y
  34728. */
  34729. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  34730. var temp = [x, y];
  34731. this.addUniform(name, temp);
  34732. };
  34733. /**
  34734. * Wrapper for addUniform.
  34735. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  34736. * @param {number} x
  34737. * @param {number} y
  34738. * @param {number} z
  34739. */
  34740. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  34741. var temp = [x, y, z];
  34742. this.addUniform(name, temp);
  34743. };
  34744. /**
  34745. * Wrapper for addUniform.
  34746. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  34747. * @param {Color3} color
  34748. */
  34749. UniformBuffer.prototype.addColor3 = function (name, color) {
  34750. var temp = new Array();
  34751. color.toArray(temp);
  34752. this.addUniform(name, temp);
  34753. };
  34754. /**
  34755. * Wrapper for addUniform.
  34756. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  34757. * @param {Color3} color
  34758. * @param {number} alpha
  34759. */
  34760. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  34761. var temp = new Array();
  34762. color.toArray(temp);
  34763. temp.push(alpha);
  34764. this.addUniform(name, temp);
  34765. };
  34766. /**
  34767. * Wrapper for addUniform.
  34768. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  34769. * @param {Vector3} vector
  34770. */
  34771. UniformBuffer.prototype.addVector3 = function (name, vector) {
  34772. var temp = new Array();
  34773. vector.toArray(temp);
  34774. this.addUniform(name, temp);
  34775. };
  34776. /**
  34777. * Wrapper for addUniform.
  34778. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  34779. */
  34780. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  34781. this.addUniform(name, 12);
  34782. };
  34783. /**
  34784. * Wrapper for addUniform.
  34785. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  34786. */
  34787. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  34788. this.addUniform(name, 8);
  34789. };
  34790. /**
  34791. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  34792. */
  34793. UniformBuffer.prototype.create = function () {
  34794. if (this._noUBO) {
  34795. return;
  34796. }
  34797. if (this._buffer) {
  34798. return; // nothing to do
  34799. }
  34800. // See spec, alignment must be filled as a vec4
  34801. this._fillAlignment(4);
  34802. this._bufferData = new Float32Array(this._data);
  34803. this._rebuild();
  34804. this._needSync = true;
  34805. };
  34806. UniformBuffer.prototype._rebuild = function () {
  34807. if (this._noUBO) {
  34808. return;
  34809. }
  34810. if (this._dynamic) {
  34811. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  34812. }
  34813. else {
  34814. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  34815. }
  34816. };
  34817. /**
  34818. * Updates the WebGL Uniform Buffer on the GPU.
  34819. * If the `dynamic` flag is set to true, no cache comparison is done.
  34820. * Otherwise, the buffer will be updated only if the cache differs.
  34821. */
  34822. UniformBuffer.prototype.update = function () {
  34823. if (!this._buffer) {
  34824. this.create();
  34825. return;
  34826. }
  34827. if (!this._dynamic && !this._needSync) {
  34828. return;
  34829. }
  34830. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  34831. this._needSync = false;
  34832. };
  34833. /**
  34834. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  34835. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  34836. * @param {number[]|Float32Array} data Flattened data
  34837. * @param {number} size Size of the data.
  34838. */
  34839. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  34840. var location = this._uniformLocations[uniformName];
  34841. if (location === undefined) {
  34842. if (this._buffer) {
  34843. // Cannot add an uniform if the buffer is already created
  34844. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  34845. return;
  34846. }
  34847. this.addUniform(uniformName, size);
  34848. location = this._uniformLocations[uniformName];
  34849. }
  34850. if (!this._buffer) {
  34851. this.create();
  34852. }
  34853. if (!this._dynamic) {
  34854. // Cache for static uniform buffers
  34855. var changed = false;
  34856. for (var i = 0; i < size; i++) {
  34857. if (this._bufferData[location + i] !== data[i]) {
  34858. changed = true;
  34859. this._bufferData[location + i] = data[i];
  34860. }
  34861. }
  34862. this._needSync = this._needSync || changed;
  34863. }
  34864. else {
  34865. // No cache for dynamic
  34866. for (var i = 0; i < size; i++) {
  34867. this._bufferData[location + i] = data[i];
  34868. }
  34869. }
  34870. };
  34871. // Update methods
  34872. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  34873. // To match std140, matrix must be realigned
  34874. for (var i = 0; i < 3; i++) {
  34875. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  34876. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  34877. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  34878. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  34879. }
  34880. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  34881. };
  34882. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  34883. this._currentEffect.setMatrix3x3(name, matrix);
  34884. };
  34885. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  34886. this._currentEffect.setMatrix2x2(name, matrix);
  34887. };
  34888. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  34889. // To match std140, matrix must be realigned
  34890. for (var i = 0; i < 2; i++) {
  34891. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  34892. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  34893. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  34894. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  34895. }
  34896. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  34897. };
  34898. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  34899. this._currentEffect.setFloat(name, x);
  34900. };
  34901. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  34902. UniformBuffer._tempBuffer[0] = x;
  34903. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  34904. };
  34905. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  34906. if (suffix === void 0) { suffix = ""; }
  34907. this._currentEffect.setFloat2(name + suffix, x, y);
  34908. };
  34909. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  34910. if (suffix === void 0) { suffix = ""; }
  34911. UniformBuffer._tempBuffer[0] = x;
  34912. UniformBuffer._tempBuffer[1] = y;
  34913. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  34914. };
  34915. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  34916. if (suffix === void 0) { suffix = ""; }
  34917. this._currentEffect.setFloat3(name + suffix, x, y, z);
  34918. };
  34919. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  34920. if (suffix === void 0) { suffix = ""; }
  34921. UniformBuffer._tempBuffer[0] = x;
  34922. UniformBuffer._tempBuffer[1] = y;
  34923. UniformBuffer._tempBuffer[2] = z;
  34924. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  34925. };
  34926. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  34927. if (suffix === void 0) { suffix = ""; }
  34928. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  34929. };
  34930. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  34931. if (suffix === void 0) { suffix = ""; }
  34932. UniformBuffer._tempBuffer[0] = x;
  34933. UniformBuffer._tempBuffer[1] = y;
  34934. UniformBuffer._tempBuffer[2] = z;
  34935. UniformBuffer._tempBuffer[3] = w;
  34936. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  34937. };
  34938. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  34939. this._currentEffect.setMatrix(name, mat);
  34940. };
  34941. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  34942. this.updateUniform(name, mat.toArray(), 16);
  34943. };
  34944. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  34945. this._currentEffect.setVector3(name, vector);
  34946. };
  34947. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  34948. vector.toArray(UniformBuffer._tempBuffer);
  34949. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  34950. };
  34951. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  34952. this._currentEffect.setVector4(name, vector);
  34953. };
  34954. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  34955. vector.toArray(UniformBuffer._tempBuffer);
  34956. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  34957. };
  34958. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  34959. if (suffix === void 0) { suffix = ""; }
  34960. this._currentEffect.setColor3(name + suffix, color);
  34961. };
  34962. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  34963. if (suffix === void 0) { suffix = ""; }
  34964. color.toArray(UniformBuffer._tempBuffer);
  34965. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  34966. };
  34967. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  34968. if (suffix === void 0) { suffix = ""; }
  34969. this._currentEffect.setColor4(name + suffix, color, alpha);
  34970. };
  34971. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  34972. if (suffix === void 0) { suffix = ""; }
  34973. color.toArray(UniformBuffer._tempBuffer);
  34974. UniformBuffer._tempBuffer[3] = alpha;
  34975. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  34976. };
  34977. /**
  34978. * Sets a sampler uniform on the effect.
  34979. * @param {string} name Name of the sampler.
  34980. * @param {Texture} texture
  34981. */
  34982. UniformBuffer.prototype.setTexture = function (name, texture) {
  34983. this._currentEffect.setTexture(name, texture);
  34984. };
  34985. /**
  34986. * Directly updates the value of the uniform in the cache AND on the GPU.
  34987. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  34988. * @param {number[]|Float32Array} data Flattened data
  34989. */
  34990. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  34991. this.updateUniform(uniformName, data, data.length);
  34992. this.update();
  34993. };
  34994. /**
  34995. * Binds this uniform buffer to an effect.
  34996. * @param {Effect} effect
  34997. * @param {string} name Name of the uniform block in the shader.
  34998. */
  34999. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  35000. this._currentEffect = effect;
  35001. if (this._noUBO || !this._buffer) {
  35002. return;
  35003. }
  35004. effect.bindUniformBuffer(this._buffer, name);
  35005. };
  35006. /**
  35007. * Disposes the uniform buffer.
  35008. */
  35009. UniformBuffer.prototype.dispose = function () {
  35010. if (this._noUBO) {
  35011. return;
  35012. }
  35013. var index = this._engine._uniformBuffers.indexOf(this);
  35014. if (index !== -1) {
  35015. this._engine._uniformBuffers.splice(index, 1);
  35016. }
  35017. if (!this._buffer) {
  35018. return;
  35019. }
  35020. if (this._engine._releaseBuffer(this._buffer)) {
  35021. this._buffer = null;
  35022. }
  35023. };
  35024. // Pool for avoiding memory leaks
  35025. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  35026. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  35027. return UniformBuffer;
  35028. }());
  35029. BABYLON.UniformBuffer = UniformBuffer;
  35030. })(BABYLON || (BABYLON = {}));
  35031. //# sourceMappingURL=babylon.uniformBuffer.js.map
  35032. "use strict";
  35033. var BABYLON;
  35034. (function (BABYLON) {
  35035. var VertexData = /** @class */ (function () {
  35036. function VertexData() {
  35037. }
  35038. VertexData.prototype.set = function (data, kind) {
  35039. switch (kind) {
  35040. case BABYLON.VertexBuffer.PositionKind:
  35041. this.positions = data;
  35042. break;
  35043. case BABYLON.VertexBuffer.NormalKind:
  35044. this.normals = data;
  35045. break;
  35046. case BABYLON.VertexBuffer.TangentKind:
  35047. this.tangents = data;
  35048. break;
  35049. case BABYLON.VertexBuffer.UVKind:
  35050. this.uvs = data;
  35051. break;
  35052. case BABYLON.VertexBuffer.UV2Kind:
  35053. this.uvs2 = data;
  35054. break;
  35055. case BABYLON.VertexBuffer.UV3Kind:
  35056. this.uvs3 = data;
  35057. break;
  35058. case BABYLON.VertexBuffer.UV4Kind:
  35059. this.uvs4 = data;
  35060. break;
  35061. case BABYLON.VertexBuffer.UV5Kind:
  35062. this.uvs5 = data;
  35063. break;
  35064. case BABYLON.VertexBuffer.UV6Kind:
  35065. this.uvs6 = data;
  35066. break;
  35067. case BABYLON.VertexBuffer.ColorKind:
  35068. this.colors = data;
  35069. break;
  35070. case BABYLON.VertexBuffer.MatricesIndicesKind:
  35071. this.matricesIndices = data;
  35072. break;
  35073. case BABYLON.VertexBuffer.MatricesWeightsKind:
  35074. this.matricesWeights = data;
  35075. break;
  35076. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  35077. this.matricesIndicesExtra = data;
  35078. break;
  35079. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  35080. this.matricesWeightsExtra = data;
  35081. break;
  35082. }
  35083. };
  35084. /**
  35085. * Associates the vertexData to the passed Mesh.
  35086. * Sets it as updatable or not (default `false`).
  35087. * Returns the VertexData.
  35088. */
  35089. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  35090. this._applyTo(mesh, updatable);
  35091. return this;
  35092. };
  35093. /**
  35094. * Associates the vertexData to the passed Geometry.
  35095. * Sets it as updatable or not (default `false`).
  35096. * Returns the VertexData.
  35097. */
  35098. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  35099. this._applyTo(geometry, updatable);
  35100. return this;
  35101. };
  35102. /**
  35103. * Updates the associated mesh.
  35104. * Returns the VertexData.
  35105. */
  35106. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  35107. this._update(mesh);
  35108. return this;
  35109. };
  35110. /**
  35111. * Updates the associated geometry.
  35112. * Returns the VertexData.
  35113. */
  35114. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  35115. this._update(geometry);
  35116. return this;
  35117. };
  35118. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  35119. if (updatable === void 0) { updatable = false; }
  35120. if (this.positions) {
  35121. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  35122. }
  35123. if (this.normals) {
  35124. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  35125. }
  35126. if (this.tangents) {
  35127. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  35128. }
  35129. if (this.uvs) {
  35130. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  35131. }
  35132. if (this.uvs2) {
  35133. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  35134. }
  35135. if (this.uvs3) {
  35136. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  35137. }
  35138. if (this.uvs4) {
  35139. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  35140. }
  35141. if (this.uvs5) {
  35142. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  35143. }
  35144. if (this.uvs6) {
  35145. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  35146. }
  35147. if (this.colors) {
  35148. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  35149. }
  35150. if (this.matricesIndices) {
  35151. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  35152. }
  35153. if (this.matricesWeights) {
  35154. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  35155. }
  35156. if (this.matricesIndicesExtra) {
  35157. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  35158. }
  35159. if (this.matricesWeightsExtra) {
  35160. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  35161. }
  35162. if (this.indices) {
  35163. meshOrGeometry.setIndices(this.indices, null, updatable);
  35164. }
  35165. return this;
  35166. };
  35167. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  35168. if (this.positions) {
  35169. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  35170. }
  35171. if (this.normals) {
  35172. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  35173. }
  35174. if (this.tangents) {
  35175. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  35176. }
  35177. if (this.uvs) {
  35178. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  35179. }
  35180. if (this.uvs2) {
  35181. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  35182. }
  35183. if (this.uvs3) {
  35184. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  35185. }
  35186. if (this.uvs4) {
  35187. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  35188. }
  35189. if (this.uvs5) {
  35190. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  35191. }
  35192. if (this.uvs6) {
  35193. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  35194. }
  35195. if (this.colors) {
  35196. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  35197. }
  35198. if (this.matricesIndices) {
  35199. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  35200. }
  35201. if (this.matricesWeights) {
  35202. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  35203. }
  35204. if (this.matricesIndicesExtra) {
  35205. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  35206. }
  35207. if (this.matricesWeightsExtra) {
  35208. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  35209. }
  35210. if (this.indices) {
  35211. meshOrGeometry.setIndices(this.indices, null);
  35212. }
  35213. return this;
  35214. };
  35215. /**
  35216. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  35217. * Returns the VertexData.
  35218. */
  35219. VertexData.prototype.transform = function (matrix) {
  35220. var transformed = BABYLON.Vector3.Zero();
  35221. var index;
  35222. if (this.positions) {
  35223. var position = BABYLON.Vector3.Zero();
  35224. for (index = 0; index < this.positions.length; index += 3) {
  35225. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  35226. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  35227. this.positions[index] = transformed.x;
  35228. this.positions[index + 1] = transformed.y;
  35229. this.positions[index + 2] = transformed.z;
  35230. }
  35231. }
  35232. if (this.normals) {
  35233. var normal = BABYLON.Vector3.Zero();
  35234. for (index = 0; index < this.normals.length; index += 3) {
  35235. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  35236. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  35237. this.normals[index] = transformed.x;
  35238. this.normals[index + 1] = transformed.y;
  35239. this.normals[index + 2] = transformed.z;
  35240. }
  35241. }
  35242. if (this.tangents) {
  35243. var tangent = BABYLON.Vector4.Zero();
  35244. var tangentTransformed = BABYLON.Vector4.Zero();
  35245. for (index = 0; index < this.tangents.length; index += 4) {
  35246. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  35247. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  35248. this.tangents[index] = tangentTransformed.x;
  35249. this.tangents[index + 1] = tangentTransformed.y;
  35250. this.tangents[index + 2] = tangentTransformed.z;
  35251. this.tangents[index + 3] = tangentTransformed.w;
  35252. }
  35253. }
  35254. return this;
  35255. };
  35256. /**
  35257. * Merges the passed VertexData into the current one.
  35258. * Returns the modified VertexData.
  35259. */
  35260. VertexData.prototype.merge = function (other) {
  35261. this._validate();
  35262. other._validate();
  35263. if (!this.normals !== !other.normals ||
  35264. !this.tangents !== !other.tangents ||
  35265. !this.uvs !== !other.uvs ||
  35266. !this.uvs2 !== !other.uvs2 ||
  35267. !this.uvs3 !== !other.uvs3 ||
  35268. !this.uvs4 !== !other.uvs4 ||
  35269. !this.uvs5 !== !other.uvs5 ||
  35270. !this.uvs6 !== !other.uvs6 ||
  35271. !this.colors !== !other.colors ||
  35272. !this.matricesIndices !== !other.matricesIndices ||
  35273. !this.matricesWeights !== !other.matricesWeights ||
  35274. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  35275. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  35276. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  35277. }
  35278. if (other.indices) {
  35279. if (!this.indices) {
  35280. this.indices = [];
  35281. }
  35282. var offset = this.positions ? this.positions.length / 3 : 0;
  35283. for (var index = 0; index < other.indices.length; index++) {
  35284. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  35285. this.indices.push(other.indices[index] + offset);
  35286. }
  35287. }
  35288. this.positions = this._mergeElement(this.positions, other.positions);
  35289. this.normals = this._mergeElement(this.normals, other.normals);
  35290. this.tangents = this._mergeElement(this.tangents, other.tangents);
  35291. this.uvs = this._mergeElement(this.uvs, other.uvs);
  35292. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  35293. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  35294. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  35295. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  35296. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  35297. this.colors = this._mergeElement(this.colors, other.colors);
  35298. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  35299. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  35300. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  35301. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  35302. return this;
  35303. };
  35304. VertexData.prototype._mergeElement = function (source, other) {
  35305. if (!source) {
  35306. return other;
  35307. }
  35308. if (!other) {
  35309. return source;
  35310. }
  35311. var len = other.length + source.length;
  35312. var isSrcTypedArray = source instanceof Float32Array;
  35313. var isOthTypedArray = other instanceof Float32Array;
  35314. // use non-loop method when the source is Float32Array
  35315. if (isSrcTypedArray) {
  35316. var ret32 = new Float32Array(len);
  35317. ret32.set(source);
  35318. ret32.set(other, source.length);
  35319. return ret32;
  35320. // source is number[], when other is also use concat
  35321. }
  35322. else if (!isOthTypedArray) {
  35323. return source.concat(other);
  35324. // source is a number[], but other is a Float32Array, loop required
  35325. }
  35326. else {
  35327. var ret = source.slice(0); // copy source to a separate array
  35328. for (var i = 0, len = other.length; i < len; i++) {
  35329. ret.push(other[i]);
  35330. }
  35331. return ret;
  35332. }
  35333. };
  35334. VertexData.prototype._validate = function () {
  35335. if (!this.positions) {
  35336. throw new Error("Positions are required");
  35337. }
  35338. var getElementCount = function (kind, values) {
  35339. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  35340. if ((values.length % stride) !== 0) {
  35341. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  35342. }
  35343. return values.length / stride;
  35344. };
  35345. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  35346. var validateElementCount = function (kind, values) {
  35347. var elementCount = getElementCount(kind, values);
  35348. if (elementCount !== positionsElementCount) {
  35349. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  35350. }
  35351. };
  35352. if (this.normals)
  35353. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  35354. if (this.tangents)
  35355. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  35356. if (this.uvs)
  35357. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  35358. if (this.uvs2)
  35359. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  35360. if (this.uvs3)
  35361. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  35362. if (this.uvs4)
  35363. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  35364. if (this.uvs5)
  35365. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  35366. if (this.uvs6)
  35367. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  35368. if (this.colors)
  35369. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  35370. if (this.matricesIndices)
  35371. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  35372. if (this.matricesWeights)
  35373. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  35374. if (this.matricesIndicesExtra)
  35375. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  35376. if (this.matricesWeightsExtra)
  35377. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  35378. };
  35379. /**
  35380. * Serializes the VertexData.
  35381. * Returns a serialized object.
  35382. */
  35383. VertexData.prototype.serialize = function () {
  35384. var serializationObject = this.serialize();
  35385. if (this.positions) {
  35386. serializationObject.positions = this.positions;
  35387. }
  35388. if (this.normals) {
  35389. serializationObject.normals = this.normals;
  35390. }
  35391. if (this.tangents) {
  35392. serializationObject.tangents = this.tangents;
  35393. }
  35394. if (this.uvs) {
  35395. serializationObject.uvs = this.uvs;
  35396. }
  35397. if (this.uvs2) {
  35398. serializationObject.uvs2 = this.uvs2;
  35399. }
  35400. if (this.uvs3) {
  35401. serializationObject.uvs3 = this.uvs3;
  35402. }
  35403. if (this.uvs4) {
  35404. serializationObject.uvs4 = this.uvs4;
  35405. }
  35406. if (this.uvs5) {
  35407. serializationObject.uvs5 = this.uvs5;
  35408. }
  35409. if (this.uvs6) {
  35410. serializationObject.uvs6 = this.uvs6;
  35411. }
  35412. if (this.colors) {
  35413. serializationObject.colors = this.colors;
  35414. }
  35415. if (this.matricesIndices) {
  35416. serializationObject.matricesIndices = this.matricesIndices;
  35417. serializationObject.matricesIndices._isExpanded = true;
  35418. }
  35419. if (this.matricesWeights) {
  35420. serializationObject.matricesWeights = this.matricesWeights;
  35421. }
  35422. if (this.matricesIndicesExtra) {
  35423. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  35424. serializationObject.matricesIndicesExtra._isExpanded = true;
  35425. }
  35426. if (this.matricesWeightsExtra) {
  35427. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  35428. }
  35429. serializationObject.indices = this.indices;
  35430. return serializationObject;
  35431. };
  35432. // Statics
  35433. /**
  35434. * Returns the object VertexData associated to the passed mesh.
  35435. */
  35436. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  35437. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  35438. };
  35439. /**
  35440. * Returns the object VertexData associated to the passed geometry.
  35441. */
  35442. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  35443. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  35444. };
  35445. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  35446. var result = new VertexData();
  35447. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35448. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  35449. }
  35450. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35451. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  35452. }
  35453. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  35454. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  35455. }
  35456. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35457. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  35458. }
  35459. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35460. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  35461. }
  35462. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  35463. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  35464. }
  35465. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  35466. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  35467. }
  35468. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  35469. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  35470. }
  35471. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  35472. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  35473. }
  35474. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35475. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  35476. }
  35477. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35478. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  35479. }
  35480. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35481. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  35482. }
  35483. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  35484. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  35485. }
  35486. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  35487. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  35488. }
  35489. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  35490. return result;
  35491. };
  35492. /**
  35493. * Creates the vertexData of the Ribbon.
  35494. */
  35495. VertexData.CreateRibbon = function (options) {
  35496. var pathArray = options.pathArray;
  35497. var closeArray = options.closeArray || false;
  35498. var closePath = options.closePath || false;
  35499. var invertUV = options.invertUV || false;
  35500. var defaultOffset = Math.floor(pathArray[0].length / 2);
  35501. var offset = options.offset || defaultOffset;
  35502. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  35503. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  35504. var customUV = options.uvs;
  35505. var customColors = options.colors;
  35506. var positions = [];
  35507. var indices = [];
  35508. var normals = [];
  35509. var uvs = [];
  35510. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  35511. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  35512. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  35513. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  35514. var minlg; // minimal length among all paths from pathArray
  35515. var lg = []; // array of path lengths : nb of vertex per path
  35516. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  35517. var p; // path iterator
  35518. var i; // point iterator
  35519. var j; // point iterator
  35520. // if single path in pathArray
  35521. if (pathArray.length < 2) {
  35522. var ar1 = [];
  35523. var ar2 = [];
  35524. for (i = 0; i < pathArray[0].length - offset; i++) {
  35525. ar1.push(pathArray[0][i]);
  35526. ar2.push(pathArray[0][i + offset]);
  35527. }
  35528. pathArray = [ar1, ar2];
  35529. }
  35530. // positions and horizontal distances (u)
  35531. var idc = 0;
  35532. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  35533. var path;
  35534. var l;
  35535. minlg = pathArray[0].length;
  35536. var vectlg;
  35537. var dist;
  35538. for (p = 0; p < pathArray.length; p++) {
  35539. uTotalDistance[p] = 0;
  35540. us[p] = [0];
  35541. path = pathArray[p];
  35542. l = path.length;
  35543. minlg = (minlg < l) ? minlg : l;
  35544. j = 0;
  35545. while (j < l) {
  35546. positions.push(path[j].x, path[j].y, path[j].z);
  35547. if (j > 0) {
  35548. vectlg = path[j].subtract(path[j - 1]).length();
  35549. dist = vectlg + uTotalDistance[p];
  35550. us[p].push(dist);
  35551. uTotalDistance[p] = dist;
  35552. }
  35553. j++;
  35554. }
  35555. if (closePath) {
  35556. j--;
  35557. positions.push(path[0].x, path[0].y, path[0].z);
  35558. vectlg = path[j].subtract(path[0]).length();
  35559. dist = vectlg + uTotalDistance[p];
  35560. us[p].push(dist);
  35561. uTotalDistance[p] = dist;
  35562. }
  35563. lg[p] = l + closePathCorr;
  35564. idx[p] = idc;
  35565. idc += (l + closePathCorr);
  35566. }
  35567. // vertical distances (v)
  35568. var path1;
  35569. var path2;
  35570. var vertex1 = null;
  35571. var vertex2 = null;
  35572. for (i = 0; i < minlg + closePathCorr; i++) {
  35573. vTotalDistance[i] = 0;
  35574. vs[i] = [0];
  35575. for (p = 0; p < pathArray.length - 1; p++) {
  35576. path1 = pathArray[p];
  35577. path2 = pathArray[p + 1];
  35578. if (i === minlg) {
  35579. vertex1 = path1[0];
  35580. vertex2 = path2[0];
  35581. }
  35582. else {
  35583. vertex1 = path1[i];
  35584. vertex2 = path2[i];
  35585. }
  35586. vectlg = vertex2.subtract(vertex1).length();
  35587. dist = vectlg + vTotalDistance[i];
  35588. vs[i].push(dist);
  35589. vTotalDistance[i] = dist;
  35590. }
  35591. if (closeArray && vertex2 && vertex1) {
  35592. path1 = pathArray[p];
  35593. path2 = pathArray[0];
  35594. if (i === minlg) {
  35595. vertex2 = path2[0];
  35596. }
  35597. vectlg = vertex2.subtract(vertex1).length();
  35598. dist = vectlg + vTotalDistance[i];
  35599. vTotalDistance[i] = dist;
  35600. }
  35601. }
  35602. // uvs
  35603. var u;
  35604. var v;
  35605. if (customUV) {
  35606. for (p = 0; p < customUV.length; p++) {
  35607. uvs.push(customUV[p].x, customUV[p].y);
  35608. }
  35609. }
  35610. else {
  35611. for (p = 0; p < pathArray.length; p++) {
  35612. for (i = 0; i < minlg + closePathCorr; i++) {
  35613. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  35614. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  35615. if (invertUV) {
  35616. uvs.push(v, u);
  35617. }
  35618. else {
  35619. uvs.push(u, v);
  35620. }
  35621. }
  35622. }
  35623. }
  35624. // indices
  35625. p = 0; // path index
  35626. var pi = 0; // positions array index
  35627. var l1 = lg[p] - 1; // path1 length
  35628. var l2 = lg[p + 1] - 1; // path2 length
  35629. var min = (l1 < l2) ? l1 : l2; // current path stop index
  35630. var shft = idx[1] - idx[0]; // shift
  35631. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  35632. while (pi <= min && p < path1nb) {
  35633. // 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
  35634. indices.push(pi, pi + shft, pi + 1);
  35635. indices.push(pi + shft + 1, pi + 1, pi + shft);
  35636. pi += 1;
  35637. if (pi === min) {
  35638. p++;
  35639. if (p === lg.length - 1) {
  35640. shft = idx[0] - idx[p];
  35641. l1 = lg[p] - 1;
  35642. l2 = lg[0] - 1;
  35643. }
  35644. else {
  35645. shft = idx[p + 1] - idx[p];
  35646. l1 = lg[p] - 1;
  35647. l2 = lg[p + 1] - 1;
  35648. }
  35649. pi = idx[p];
  35650. min = (l1 < l2) ? l1 + pi : l2 + pi;
  35651. }
  35652. }
  35653. // normals
  35654. VertexData.ComputeNormals(positions, indices, normals);
  35655. if (closePath) {
  35656. var indexFirst = 0;
  35657. var indexLast = 0;
  35658. for (p = 0; p < pathArray.length; p++) {
  35659. indexFirst = idx[p] * 3;
  35660. if (p + 1 < pathArray.length) {
  35661. indexLast = (idx[p + 1] - 1) * 3;
  35662. }
  35663. else {
  35664. indexLast = normals.length - 3;
  35665. }
  35666. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  35667. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  35668. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  35669. normals[indexLast] = normals[indexFirst];
  35670. normals[indexLast + 1] = normals[indexFirst + 1];
  35671. normals[indexLast + 2] = normals[indexFirst + 2];
  35672. }
  35673. }
  35674. // sides
  35675. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  35676. // Colors
  35677. var colors = null;
  35678. if (customColors) {
  35679. colors = new Float32Array(customColors.length * 4);
  35680. for (var c = 0; c < customColors.length; c++) {
  35681. colors[c * 4] = customColors[c].r;
  35682. colors[c * 4 + 1] = customColors[c].g;
  35683. colors[c * 4 + 2] = customColors[c].b;
  35684. colors[c * 4 + 3] = customColors[c].a;
  35685. }
  35686. }
  35687. // Result
  35688. var vertexData = new VertexData();
  35689. var positions32 = new Float32Array(positions);
  35690. var normals32 = new Float32Array(normals);
  35691. var uvs32 = new Float32Array(uvs);
  35692. vertexData.indices = indices;
  35693. vertexData.positions = positions32;
  35694. vertexData.normals = normals32;
  35695. vertexData.uvs = uvs32;
  35696. if (colors) {
  35697. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  35698. }
  35699. if (closePath) {
  35700. vertexData._idx = idx;
  35701. }
  35702. return vertexData;
  35703. };
  35704. /**
  35705. * Creates the VertexData of the Box.
  35706. */
  35707. VertexData.CreateBox = function (options) {
  35708. var normalsSource = [
  35709. new BABYLON.Vector3(0, 0, 1),
  35710. new BABYLON.Vector3(0, 0, -1),
  35711. new BABYLON.Vector3(1, 0, 0),
  35712. new BABYLON.Vector3(-1, 0, 0),
  35713. new BABYLON.Vector3(0, 1, 0),
  35714. new BABYLON.Vector3(0, -1, 0)
  35715. ];
  35716. var indices = [];
  35717. var positions = [];
  35718. var normals = [];
  35719. var uvs = [];
  35720. var width = options.width || options.size || 1;
  35721. var height = options.height || options.size || 1;
  35722. var depth = options.depth || options.size || 1;
  35723. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  35724. var faceUV = options.faceUV || new Array(6);
  35725. var faceColors = options.faceColors;
  35726. var colors = [];
  35727. // default face colors and UV if undefined
  35728. for (var f = 0; f < 6; f++) {
  35729. if (faceUV[f] === undefined) {
  35730. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  35731. }
  35732. if (faceColors && faceColors[f] === undefined) {
  35733. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  35734. }
  35735. }
  35736. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  35737. // Create each face in turn.
  35738. for (var index = 0; index < normalsSource.length; index++) {
  35739. var normal = normalsSource[index];
  35740. // Get two vectors perpendicular to the face normal and to each other.
  35741. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  35742. var side2 = BABYLON.Vector3.Cross(normal, side1);
  35743. // Six indices (two triangles) per face.
  35744. var verticesLength = positions.length / 3;
  35745. indices.push(verticesLength);
  35746. indices.push(verticesLength + 1);
  35747. indices.push(verticesLength + 2);
  35748. indices.push(verticesLength);
  35749. indices.push(verticesLength + 2);
  35750. indices.push(verticesLength + 3);
  35751. // Four vertices per face.
  35752. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  35753. positions.push(vertex.x, vertex.y, vertex.z);
  35754. normals.push(normal.x, normal.y, normal.z);
  35755. uvs.push(faceUV[index].z, faceUV[index].w);
  35756. if (faceColors) {
  35757. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  35758. }
  35759. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  35760. positions.push(vertex.x, vertex.y, vertex.z);
  35761. normals.push(normal.x, normal.y, normal.z);
  35762. uvs.push(faceUV[index].x, faceUV[index].w);
  35763. if (faceColors) {
  35764. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  35765. }
  35766. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  35767. positions.push(vertex.x, vertex.y, vertex.z);
  35768. normals.push(normal.x, normal.y, normal.z);
  35769. uvs.push(faceUV[index].x, faceUV[index].y);
  35770. if (faceColors) {
  35771. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  35772. }
  35773. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  35774. positions.push(vertex.x, vertex.y, vertex.z);
  35775. normals.push(normal.x, normal.y, normal.z);
  35776. uvs.push(faceUV[index].z, faceUV[index].y);
  35777. if (faceColors) {
  35778. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  35779. }
  35780. }
  35781. // sides
  35782. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  35783. // Result
  35784. var vertexData = new VertexData();
  35785. vertexData.indices = indices;
  35786. vertexData.positions = positions;
  35787. vertexData.normals = normals;
  35788. vertexData.uvs = uvs;
  35789. if (faceColors) {
  35790. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  35791. vertexData.colors = totalColors;
  35792. }
  35793. return vertexData;
  35794. };
  35795. /**
  35796. * Creates the VertexData of the Sphere.
  35797. */
  35798. VertexData.CreateSphere = function (options) {
  35799. var segments = options.segments || 32;
  35800. var diameterX = options.diameterX || options.diameter || 1;
  35801. var diameterY = options.diameterY || options.diameter || 1;
  35802. var diameterZ = options.diameterZ || options.diameter || 1;
  35803. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  35804. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  35805. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  35806. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  35807. var totalZRotationSteps = 2 + segments;
  35808. var totalYRotationSteps = 2 * totalZRotationSteps;
  35809. var indices = [];
  35810. var positions = [];
  35811. var normals = [];
  35812. var uvs = [];
  35813. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  35814. var normalizedZ = zRotationStep / totalZRotationSteps;
  35815. var angleZ = normalizedZ * Math.PI * slice;
  35816. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  35817. var normalizedY = yRotationStep / totalYRotationSteps;
  35818. var angleY = normalizedY * Math.PI * 2 * arc;
  35819. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  35820. var rotationY = BABYLON.Matrix.RotationY(angleY);
  35821. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  35822. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  35823. var vertex = complete.multiply(radius);
  35824. var normal = complete.divide(radius).normalize();
  35825. positions.push(vertex.x, vertex.y, vertex.z);
  35826. normals.push(normal.x, normal.y, normal.z);
  35827. uvs.push(normalizedY, normalizedZ);
  35828. }
  35829. if (zRotationStep > 0) {
  35830. var verticesCount = positions.length / 3;
  35831. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  35832. indices.push((firstIndex));
  35833. indices.push((firstIndex + 1));
  35834. indices.push(firstIndex + totalYRotationSteps + 1);
  35835. indices.push((firstIndex + totalYRotationSteps + 1));
  35836. indices.push((firstIndex + 1));
  35837. indices.push((firstIndex + totalYRotationSteps + 2));
  35838. }
  35839. }
  35840. }
  35841. // Sides
  35842. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  35843. // Result
  35844. var vertexData = new VertexData();
  35845. vertexData.indices = indices;
  35846. vertexData.positions = positions;
  35847. vertexData.normals = normals;
  35848. vertexData.uvs = uvs;
  35849. return vertexData;
  35850. };
  35851. /**
  35852. * Creates the VertexData of the Cylinder or Cone.
  35853. */
  35854. VertexData.CreateCylinder = function (options) {
  35855. var height = options.height || 2;
  35856. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  35857. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  35858. var tessellation = options.tessellation || 24;
  35859. var subdivisions = options.subdivisions || 1;
  35860. var hasRings = options.hasRings ? true : false;
  35861. var enclose = options.enclose ? true : false;
  35862. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  35863. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  35864. var faceUV = options.faceUV || new Array(3);
  35865. var faceColors = options.faceColors;
  35866. // default face colors and UV if undefined
  35867. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  35868. var ringNb = (hasRings) ? subdivisions : 1;
  35869. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  35870. var f;
  35871. for (f = 0; f < surfaceNb; f++) {
  35872. if (faceColors && faceColors[f] === undefined) {
  35873. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  35874. }
  35875. }
  35876. for (f = 0; f < surfaceNb; f++) {
  35877. if (faceUV && faceUV[f] === undefined) {
  35878. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  35879. }
  35880. }
  35881. var indices = new Array();
  35882. var positions = new Array();
  35883. var normals = new Array();
  35884. var uvs = new Array();
  35885. var colors = new Array();
  35886. var angle_step = Math.PI * 2 * arc / tessellation;
  35887. var angle;
  35888. var h;
  35889. var radius;
  35890. var tan = (diameterBottom - diameterTop) / 2 / height;
  35891. var ringVertex = BABYLON.Vector3.Zero();
  35892. var ringNormal = BABYLON.Vector3.Zero();
  35893. var ringFirstVertex = BABYLON.Vector3.Zero();
  35894. var ringFirstNormal = BABYLON.Vector3.Zero();
  35895. var quadNormal = BABYLON.Vector3.Zero();
  35896. var Y = BABYLON.Axis.Y;
  35897. // positions, normals, uvs
  35898. var i;
  35899. var j;
  35900. var r;
  35901. var ringIdx = 1;
  35902. var s = 1; // surface index
  35903. var cs = 0;
  35904. var v = 0;
  35905. for (i = 0; i <= subdivisions; i++) {
  35906. h = i / subdivisions;
  35907. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  35908. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  35909. for (r = 0; r < ringIdx; r++) {
  35910. if (hasRings) {
  35911. s += r;
  35912. }
  35913. if (enclose) {
  35914. s += 2 * r;
  35915. }
  35916. for (j = 0; j <= tessellation; j++) {
  35917. angle = j * angle_step;
  35918. // position
  35919. ringVertex.x = Math.cos(-angle) * radius;
  35920. ringVertex.y = -height / 2 + h * height;
  35921. ringVertex.z = Math.sin(-angle) * radius;
  35922. // normal
  35923. if (diameterTop === 0 && i === subdivisions) {
  35924. // if no top cap, reuse former normals
  35925. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  35926. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  35927. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  35928. }
  35929. else {
  35930. ringNormal.x = ringVertex.x;
  35931. ringNormal.z = ringVertex.z;
  35932. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  35933. ringNormal.normalize();
  35934. }
  35935. // keep first ring vertex values for enclose
  35936. if (j === 0) {
  35937. ringFirstVertex.copyFrom(ringVertex);
  35938. ringFirstNormal.copyFrom(ringNormal);
  35939. }
  35940. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  35941. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  35942. if (hasRings) {
  35943. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  35944. }
  35945. else {
  35946. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  35947. }
  35948. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  35949. if (faceColors) {
  35950. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  35951. }
  35952. }
  35953. // if enclose, add four vertices and their dedicated normals
  35954. if (arc !== 1 && enclose) {
  35955. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  35956. positions.push(0, ringVertex.y, 0);
  35957. positions.push(0, ringVertex.y, 0);
  35958. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  35959. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  35960. quadNormal.normalize();
  35961. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  35962. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  35963. quadNormal.normalize();
  35964. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  35965. if (hasRings) {
  35966. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  35967. }
  35968. else {
  35969. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  35970. }
  35971. uvs.push(faceUV[s + 1].x, v);
  35972. uvs.push(faceUV[s + 1].z, v);
  35973. if (hasRings) {
  35974. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  35975. }
  35976. else {
  35977. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  35978. }
  35979. uvs.push(faceUV[s + 2].x, v);
  35980. uvs.push(faceUV[s + 2].z, v);
  35981. if (faceColors) {
  35982. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  35983. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  35984. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  35985. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  35986. }
  35987. }
  35988. if (cs !== s) {
  35989. cs = s;
  35990. }
  35991. }
  35992. }
  35993. // indices
  35994. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  35995. var s;
  35996. i = 0;
  35997. for (s = 0; s < subdivisions; s++) {
  35998. var i0 = 0;
  35999. var i1 = 0;
  36000. var i2 = 0;
  36001. var i3 = 0;
  36002. for (j = 0; j < tessellation; j++) {
  36003. i0 = i * (e + 1) + j;
  36004. i1 = (i + 1) * (e + 1) + j;
  36005. i2 = i * (e + 1) + (j + 1);
  36006. i3 = (i + 1) * (e + 1) + (j + 1);
  36007. indices.push(i0, i1, i2);
  36008. indices.push(i3, i2, i1);
  36009. }
  36010. if (arc !== 1 && enclose) {
  36011. indices.push(i0 + 2, i1 + 2, i2 + 2);
  36012. indices.push(i3 + 2, i2 + 2, i1 + 2);
  36013. indices.push(i0 + 4, i1 + 4, i2 + 4);
  36014. indices.push(i3 + 4, i2 + 4, i1 + 4);
  36015. }
  36016. i = (hasRings) ? (i + 2) : (i + 1);
  36017. }
  36018. // Caps
  36019. var createCylinderCap = function (isTop) {
  36020. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  36021. if (radius === 0) {
  36022. return;
  36023. }
  36024. // Cap positions, normals & uvs
  36025. var angle;
  36026. var circleVector;
  36027. var i;
  36028. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  36029. var c = null;
  36030. if (faceColors) {
  36031. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  36032. }
  36033. // cap center
  36034. var vbase = positions.length / 3;
  36035. var offset = isTop ? height / 2 : -height / 2;
  36036. var center = new BABYLON.Vector3(0, offset, 0);
  36037. positions.push(center.x, center.y, center.z);
  36038. normals.push(0, isTop ? 1 : -1, 0);
  36039. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  36040. if (c) {
  36041. colors.push(c.r, c.g, c.b, c.a);
  36042. }
  36043. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  36044. for (i = 0; i <= tessellation; i++) {
  36045. angle = Math.PI * 2 * i * arc / tessellation;
  36046. var cos = Math.cos(-angle);
  36047. var sin = Math.sin(-angle);
  36048. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  36049. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  36050. positions.push(circleVector.x, circleVector.y, circleVector.z);
  36051. normals.push(0, isTop ? 1 : -1, 0);
  36052. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  36053. if (c) {
  36054. colors.push(c.r, c.g, c.b, c.a);
  36055. }
  36056. }
  36057. // Cap indices
  36058. for (i = 0; i < tessellation; i++) {
  36059. if (!isTop) {
  36060. indices.push(vbase);
  36061. indices.push(vbase + (i + 1));
  36062. indices.push(vbase + (i + 2));
  36063. }
  36064. else {
  36065. indices.push(vbase);
  36066. indices.push(vbase + (i + 2));
  36067. indices.push(vbase + (i + 1));
  36068. }
  36069. }
  36070. };
  36071. // add caps to geometry
  36072. createCylinderCap(false);
  36073. createCylinderCap(true);
  36074. // Sides
  36075. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36076. var vertexData = new VertexData();
  36077. vertexData.indices = indices;
  36078. vertexData.positions = positions;
  36079. vertexData.normals = normals;
  36080. vertexData.uvs = uvs;
  36081. if (faceColors) {
  36082. vertexData.colors = colors;
  36083. }
  36084. return vertexData;
  36085. };
  36086. /**
  36087. * Creates the VertexData of the Torus.
  36088. */
  36089. VertexData.CreateTorus = function (options) {
  36090. var indices = [];
  36091. var positions = [];
  36092. var normals = [];
  36093. var uvs = [];
  36094. var diameter = options.diameter || 1;
  36095. var thickness = options.thickness || 0.5;
  36096. var tessellation = options.tessellation || 16;
  36097. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36098. var stride = tessellation + 1;
  36099. for (var i = 0; i <= tessellation; i++) {
  36100. var u = i / tessellation;
  36101. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  36102. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  36103. for (var j = 0; j <= tessellation; j++) {
  36104. var v = 1 - j / tessellation;
  36105. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  36106. var dx = Math.cos(innerAngle);
  36107. var dy = Math.sin(innerAngle);
  36108. // Create a vertex.
  36109. var normal = new BABYLON.Vector3(dx, dy, 0);
  36110. var position = normal.scale(thickness / 2);
  36111. var textureCoordinate = new BABYLON.Vector2(u, v);
  36112. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  36113. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  36114. positions.push(position.x, position.y, position.z);
  36115. normals.push(normal.x, normal.y, normal.z);
  36116. uvs.push(textureCoordinate.x, textureCoordinate.y);
  36117. // And create indices for two triangles.
  36118. var nextI = (i + 1) % stride;
  36119. var nextJ = (j + 1) % stride;
  36120. indices.push(i * stride + j);
  36121. indices.push(i * stride + nextJ);
  36122. indices.push(nextI * stride + j);
  36123. indices.push(i * stride + nextJ);
  36124. indices.push(nextI * stride + nextJ);
  36125. indices.push(nextI * stride + j);
  36126. }
  36127. }
  36128. // Sides
  36129. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36130. // Result
  36131. var vertexData = new VertexData();
  36132. vertexData.indices = indices;
  36133. vertexData.positions = positions;
  36134. vertexData.normals = normals;
  36135. vertexData.uvs = uvs;
  36136. return vertexData;
  36137. };
  36138. /**
  36139. * Creates the VertexData of the LineSystem.
  36140. */
  36141. VertexData.CreateLineSystem = function (options) {
  36142. var indices = [];
  36143. var positions = [];
  36144. var lines = options.lines;
  36145. var colors = options.colors;
  36146. var vertexColors = [];
  36147. var idx = 0;
  36148. for (var l = 0; l < lines.length; l++) {
  36149. var points = lines[l];
  36150. for (var index = 0; index < points.length; index++) {
  36151. positions.push(points[index].x, points[index].y, points[index].z);
  36152. if (colors) {
  36153. var color = colors[l];
  36154. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  36155. }
  36156. if (index > 0) {
  36157. indices.push(idx - 1);
  36158. indices.push(idx);
  36159. }
  36160. idx++;
  36161. }
  36162. }
  36163. var vertexData = new VertexData();
  36164. vertexData.indices = indices;
  36165. vertexData.positions = positions;
  36166. if (colors) {
  36167. vertexData.colors = vertexColors;
  36168. }
  36169. return vertexData;
  36170. };
  36171. /**
  36172. * Create the VertexData of the DashedLines.
  36173. */
  36174. VertexData.CreateDashedLines = function (options) {
  36175. var dashSize = options.dashSize || 3;
  36176. var gapSize = options.gapSize || 1;
  36177. var dashNb = options.dashNb || 200;
  36178. var points = options.points;
  36179. var positions = new Array();
  36180. var indices = new Array();
  36181. var curvect = BABYLON.Vector3.Zero();
  36182. var lg = 0;
  36183. var nb = 0;
  36184. var shft = 0;
  36185. var dashshft = 0;
  36186. var curshft = 0;
  36187. var idx = 0;
  36188. var i = 0;
  36189. for (i = 0; i < points.length - 1; i++) {
  36190. points[i + 1].subtractToRef(points[i], curvect);
  36191. lg += curvect.length();
  36192. }
  36193. shft = lg / dashNb;
  36194. dashshft = dashSize * shft / (dashSize + gapSize);
  36195. for (i = 0; i < points.length - 1; i++) {
  36196. points[i + 1].subtractToRef(points[i], curvect);
  36197. nb = Math.floor(curvect.length() / shft);
  36198. curvect.normalize();
  36199. for (var j = 0; j < nb; j++) {
  36200. curshft = shft * j;
  36201. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  36202. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  36203. indices.push(idx, idx + 1);
  36204. idx += 2;
  36205. }
  36206. }
  36207. // Result
  36208. var vertexData = new VertexData();
  36209. vertexData.positions = positions;
  36210. vertexData.indices = indices;
  36211. return vertexData;
  36212. };
  36213. /**
  36214. * Creates the VertexData of the Ground.
  36215. */
  36216. VertexData.CreateGround = function (options) {
  36217. var indices = [];
  36218. var positions = [];
  36219. var normals = [];
  36220. var uvs = [];
  36221. var row, col;
  36222. var width = options.width || 1;
  36223. var height = options.height || 1;
  36224. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  36225. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  36226. for (row = 0; row <= subdivisionsY; row++) {
  36227. for (col = 0; col <= subdivisionsX; col++) {
  36228. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  36229. var normal = new BABYLON.Vector3(0, 1.0, 0);
  36230. positions.push(position.x, position.y, position.z);
  36231. normals.push(normal.x, normal.y, normal.z);
  36232. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  36233. }
  36234. }
  36235. for (row = 0; row < subdivisionsY; row++) {
  36236. for (col = 0; col < subdivisionsX; col++) {
  36237. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  36238. indices.push(col + 1 + row * (subdivisionsX + 1));
  36239. indices.push(col + row * (subdivisionsX + 1));
  36240. indices.push(col + (row + 1) * (subdivisionsX + 1));
  36241. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  36242. indices.push(col + row * (subdivisionsX + 1));
  36243. }
  36244. }
  36245. // Result
  36246. var vertexData = new VertexData();
  36247. vertexData.indices = indices;
  36248. vertexData.positions = positions;
  36249. vertexData.normals = normals;
  36250. vertexData.uvs = uvs;
  36251. return vertexData;
  36252. };
  36253. /**
  36254. * Creates the VertexData of the TiledGround.
  36255. */
  36256. VertexData.CreateTiledGround = function (options) {
  36257. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  36258. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  36259. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  36260. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  36261. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  36262. var precision = options.precision || { w: 1, h: 1 };
  36263. var indices = new Array();
  36264. var positions = new Array();
  36265. var normals = new Array();
  36266. var uvs = new Array();
  36267. var row, col, tileRow, tileCol;
  36268. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  36269. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  36270. precision.w = (precision.w < 1) ? 1 : precision.w;
  36271. precision.h = (precision.h < 1) ? 1 : precision.h;
  36272. var tileSize = {
  36273. 'w': (xmax - xmin) / subdivisions.w,
  36274. 'h': (zmax - zmin) / subdivisions.h
  36275. };
  36276. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  36277. // Indices
  36278. var base = positions.length / 3;
  36279. var rowLength = precision.w + 1;
  36280. for (row = 0; row < precision.h; row++) {
  36281. for (col = 0; col < precision.w; col++) {
  36282. var square = [
  36283. base + col + row * rowLength,
  36284. base + (col + 1) + row * rowLength,
  36285. base + (col + 1) + (row + 1) * rowLength,
  36286. base + col + (row + 1) * rowLength
  36287. ];
  36288. indices.push(square[1]);
  36289. indices.push(square[2]);
  36290. indices.push(square[3]);
  36291. indices.push(square[0]);
  36292. indices.push(square[1]);
  36293. indices.push(square[3]);
  36294. }
  36295. }
  36296. // Position, normals and uvs
  36297. var position = BABYLON.Vector3.Zero();
  36298. var normal = new BABYLON.Vector3(0, 1.0, 0);
  36299. for (row = 0; row <= precision.h; row++) {
  36300. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  36301. for (col = 0; col <= precision.w; col++) {
  36302. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  36303. position.y = 0;
  36304. positions.push(position.x, position.y, position.z);
  36305. normals.push(normal.x, normal.y, normal.z);
  36306. uvs.push(col / precision.w, row / precision.h);
  36307. }
  36308. }
  36309. }
  36310. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  36311. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  36312. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  36313. }
  36314. }
  36315. // Result
  36316. var vertexData = new VertexData();
  36317. vertexData.indices = indices;
  36318. vertexData.positions = positions;
  36319. vertexData.normals = normals;
  36320. vertexData.uvs = uvs;
  36321. return vertexData;
  36322. };
  36323. /**
  36324. * Creates the VertexData of the Ground designed from a heightmap.
  36325. */
  36326. VertexData.CreateGroundFromHeightMap = function (options) {
  36327. var indices = [];
  36328. var positions = [];
  36329. var normals = [];
  36330. var uvs = [];
  36331. var row, col;
  36332. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  36333. // Vertices
  36334. for (row = 0; row <= options.subdivisions; row++) {
  36335. for (col = 0; col <= options.subdivisions; col++) {
  36336. 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));
  36337. // Compute height
  36338. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  36339. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  36340. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  36341. var r = options.buffer[pos] / 255.0;
  36342. var g = options.buffer[pos + 1] / 255.0;
  36343. var b = options.buffer[pos + 2] / 255.0;
  36344. var gradient = r * filter.r + g * filter.g + b * filter.b;
  36345. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  36346. // Add vertex
  36347. positions.push(position.x, position.y, position.z);
  36348. normals.push(0, 0, 0);
  36349. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  36350. }
  36351. }
  36352. // Indices
  36353. for (row = 0; row < options.subdivisions; row++) {
  36354. for (col = 0; col < options.subdivisions; col++) {
  36355. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  36356. indices.push(col + 1 + row * (options.subdivisions + 1));
  36357. indices.push(col + row * (options.subdivisions + 1));
  36358. indices.push(col + (row + 1) * (options.subdivisions + 1));
  36359. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  36360. indices.push(col + row * (options.subdivisions + 1));
  36361. }
  36362. }
  36363. // Normals
  36364. VertexData.ComputeNormals(positions, indices, normals);
  36365. // Result
  36366. var vertexData = new VertexData();
  36367. vertexData.indices = indices;
  36368. vertexData.positions = positions;
  36369. vertexData.normals = normals;
  36370. vertexData.uvs = uvs;
  36371. return vertexData;
  36372. };
  36373. /**
  36374. * Creates the VertexData of the Plane.
  36375. */
  36376. VertexData.CreatePlane = function (options) {
  36377. var indices = [];
  36378. var positions = [];
  36379. var normals = [];
  36380. var uvs = [];
  36381. var width = options.width || options.size || 1;
  36382. var height = options.height || options.size || 1;
  36383. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36384. // Vertices
  36385. var halfWidth = width / 2.0;
  36386. var halfHeight = height / 2.0;
  36387. positions.push(-halfWidth, -halfHeight, 0);
  36388. normals.push(0, 0, -1.0);
  36389. uvs.push(0.0, 0.0);
  36390. positions.push(halfWidth, -halfHeight, 0);
  36391. normals.push(0, 0, -1.0);
  36392. uvs.push(1.0, 0.0);
  36393. positions.push(halfWidth, halfHeight, 0);
  36394. normals.push(0, 0, -1.0);
  36395. uvs.push(1.0, 1.0);
  36396. positions.push(-halfWidth, halfHeight, 0);
  36397. normals.push(0, 0, -1.0);
  36398. uvs.push(0.0, 1.0);
  36399. // Indices
  36400. indices.push(0);
  36401. indices.push(1);
  36402. indices.push(2);
  36403. indices.push(0);
  36404. indices.push(2);
  36405. indices.push(3);
  36406. // Sides
  36407. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36408. // Result
  36409. var vertexData = new VertexData();
  36410. vertexData.indices = indices;
  36411. vertexData.positions = positions;
  36412. vertexData.normals = normals;
  36413. vertexData.uvs = uvs;
  36414. return vertexData;
  36415. };
  36416. /**
  36417. * Creates the VertexData of the Disc or regular Polygon.
  36418. */
  36419. VertexData.CreateDisc = function (options) {
  36420. var positions = new Array();
  36421. var indices = new Array();
  36422. var normals = new Array();
  36423. var uvs = new Array();
  36424. var radius = options.radius || 0.5;
  36425. var tessellation = options.tessellation || 64;
  36426. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36427. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36428. // positions and uvs
  36429. positions.push(0, 0, 0); // disc center first
  36430. uvs.push(0.5, 0.5);
  36431. var theta = Math.PI * 2 * arc;
  36432. var step = theta / tessellation;
  36433. for (var a = 0; a < theta; a += step) {
  36434. var x = Math.cos(a);
  36435. var y = Math.sin(a);
  36436. var u = (x + 1) / 2;
  36437. var v = (1 - y) / 2;
  36438. positions.push(radius * x, radius * y, 0);
  36439. uvs.push(u, v);
  36440. }
  36441. if (arc === 1) {
  36442. positions.push(positions[3], positions[4], positions[5]); // close the circle
  36443. uvs.push(uvs[2], uvs[3]);
  36444. }
  36445. //indices
  36446. var vertexNb = positions.length / 3;
  36447. for (var i = 1; i < vertexNb - 1; i++) {
  36448. indices.push(i + 1, 0, i);
  36449. }
  36450. // result
  36451. VertexData.ComputeNormals(positions, indices, normals);
  36452. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36453. var vertexData = new VertexData();
  36454. vertexData.indices = indices;
  36455. vertexData.positions = positions;
  36456. vertexData.normals = normals;
  36457. vertexData.uvs = uvs;
  36458. return vertexData;
  36459. };
  36460. /**
  36461. * Re-creates the VertexData of the Polygon for sideOrientation.
  36462. */
  36463. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  36464. var faceUV = fUV || new Array(3);
  36465. var faceColors = fColors;
  36466. var colors = [];
  36467. // default face colors and UV if undefined
  36468. for (var f = 0; f < 3; f++) {
  36469. if (faceUV[f] === undefined) {
  36470. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36471. }
  36472. if (faceColors && faceColors[f] === undefined) {
  36473. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36474. }
  36475. }
  36476. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36477. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  36478. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36479. var indices = polygon.getIndices();
  36480. // set face colours and textures
  36481. var idx = 0;
  36482. var face = 0;
  36483. for (var index = 0; index < normals.length; index += 3) {
  36484. //Edge Face no. 1
  36485. if (Math.abs(normals[index + 1]) < 0.001) {
  36486. face = 1;
  36487. }
  36488. //Top Face no. 0
  36489. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  36490. face = 0;
  36491. }
  36492. //Bottom Face no. 2
  36493. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  36494. face = 2;
  36495. }
  36496. idx = index / 3;
  36497. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  36498. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  36499. if (faceColors) {
  36500. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  36501. }
  36502. }
  36503. // sides
  36504. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  36505. // Result
  36506. var vertexData = new VertexData();
  36507. vertexData.indices = indices;
  36508. vertexData.positions = positions;
  36509. vertexData.normals = normals;
  36510. vertexData.uvs = uvs;
  36511. if (faceColors) {
  36512. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36513. vertexData.colors = totalColors;
  36514. }
  36515. return vertexData;
  36516. };
  36517. /**
  36518. * Creates the VertexData of the IcoSphere.
  36519. */
  36520. VertexData.CreateIcoSphere = function (options) {
  36521. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36522. var radius = options.radius || 1;
  36523. var flat = (options.flat === undefined) ? true : options.flat;
  36524. var subdivisions = options.subdivisions || 4;
  36525. var radiusX = options.radiusX || radius;
  36526. var radiusY = options.radiusY || radius;
  36527. var radiusZ = options.radiusZ || radius;
  36528. var t = (1 + Math.sqrt(5)) / 2;
  36529. // 12 vertex x,y,z
  36530. var ico_vertices = [
  36531. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  36532. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  36533. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  36534. ];
  36535. // index of 3 vertex makes a face of icopshere
  36536. var ico_indices = [
  36537. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  36538. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  36539. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  36540. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  36541. ];
  36542. // vertex for uv have aliased position, not for UV
  36543. var vertices_unalias_id = [
  36544. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  36545. // vertex alias
  36546. 0,
  36547. 2,
  36548. 3,
  36549. 3,
  36550. 3,
  36551. 4,
  36552. 7,
  36553. 8,
  36554. 9,
  36555. 9,
  36556. 10,
  36557. 11 // 23: B + 12
  36558. ];
  36559. // uv as integer step (not pixels !)
  36560. var ico_vertexuv = [
  36561. 5, 1, 3, 1, 6, 4, 0, 0,
  36562. 5, 3, 4, 2, 2, 2, 4, 0,
  36563. 2, 0, 1, 1, 6, 0, 6, 2,
  36564. // vertex alias (for same vertex on different faces)
  36565. 0, 4,
  36566. 3, 3,
  36567. 4, 4,
  36568. 3, 1,
  36569. 4, 2,
  36570. 4, 4,
  36571. 0, 2,
  36572. 1, 1,
  36573. 2, 2,
  36574. 3, 3,
  36575. 1, 3,
  36576. 2, 4 // 23: B + 12
  36577. ];
  36578. // Vertices[0, 1, ...9, A, B] : position on UV plane
  36579. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  36580. // First island of uv mapping
  36581. // v = 4h 3+ 2
  36582. // v = 3h 9+ 4
  36583. // v = 2h 9+ 5 B
  36584. // v = 1h 9 1 0
  36585. // v = 0h 3 8 7 A
  36586. // u = 0 1 2 3 4 5 6 *a
  36587. // Second island of uv mapping
  36588. // v = 4h 0+ B+ 4+
  36589. // v = 3h A+ 2+
  36590. // v = 2h 7+ 6 3+
  36591. // v = 1h 8+ 3+
  36592. // v = 0h
  36593. // u = 0 1 2 3 4 5 6 *a
  36594. // Face layout on texture UV mapping
  36595. // ============
  36596. // \ 4 /\ 16 / ======
  36597. // \ / \ / /\ 11 /
  36598. // \/ 7 \/ / \ /
  36599. // ======= / 10 \/
  36600. // /\ 17 /\ =======
  36601. // / \ / \ \ 15 /\
  36602. // / 8 \/ 12 \ \ / \
  36603. // ============ \/ 6 \
  36604. // \ 18 /\ ============
  36605. // \ / \ \ 5 /\ 0 /
  36606. // \/ 13 \ \ / \ /
  36607. // ======= \/ 1 \/
  36608. // =============
  36609. // /\ 19 /\ 2 /\
  36610. // / \ / \ / \
  36611. // / 14 \/ 9 \/ 3 \
  36612. // ===================
  36613. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  36614. var ustep = 138 / 1024;
  36615. var vstep = 239 / 1024;
  36616. var uoffset = 60 / 1024;
  36617. var voffset = 26 / 1024;
  36618. // Second island should have margin, not to touch the first island
  36619. // avoid any borderline artefact in pixel rounding
  36620. var island_u_offset = -40 / 1024;
  36621. var island_v_offset = +20 / 1024;
  36622. // face is either island 0 or 1 :
  36623. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  36624. var island = [
  36625. 0, 0, 0, 0, 1,
  36626. 0, 0, 1, 1, 0,
  36627. 0, 0, 1, 1, 0,
  36628. 0, 1, 1, 1, 0 // 15 - 19
  36629. ];
  36630. var indices = new Array();
  36631. var positions = new Array();
  36632. var normals = new Array();
  36633. var uvs = new Array();
  36634. var current_indice = 0;
  36635. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  36636. var face_vertex_pos = new Array(3);
  36637. var face_vertex_uv = new Array(3);
  36638. var v012;
  36639. for (v012 = 0; v012 < 3; v012++) {
  36640. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  36641. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  36642. }
  36643. // create all with normals
  36644. for (var face = 0; face < 20; face++) {
  36645. // 3 vertex per face
  36646. for (v012 = 0; v012 < 3; v012++) {
  36647. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  36648. var v_id = ico_indices[3 * face + v012];
  36649. // vertex have 3D position (x,y,z)
  36650. 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]);
  36651. // Normalize to get normal, then scale to radius
  36652. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  36653. // uv Coordinates from vertex ID
  36654. 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);
  36655. }
  36656. // Subdivide the face (interpolate pos, norm, uv)
  36657. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  36658. // - norm is linear interpolation of vertex corner normal
  36659. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  36660. // - uv is linear interpolation
  36661. //
  36662. // Topology is as below for sub-divide by 2
  36663. // vertex shown as v0,v1,v2
  36664. // interp index is i1 to progress in range [v0,v1[
  36665. // interp index is i2 to progress in range [v0,v2[
  36666. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  36667. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  36668. //
  36669. //
  36670. // i2 v2
  36671. // ^ ^
  36672. // / / \
  36673. // / / \
  36674. // / / \
  36675. // / / (0,1) \
  36676. // / #---------\
  36677. // / / \ (0,0)'/ \
  36678. // / / \ / \
  36679. // / / \ / \
  36680. // / / (0,0) \ / (1,0) \
  36681. // / #---------#---------\
  36682. // v0 v1
  36683. //
  36684. // --------------------> i1
  36685. //
  36686. // interp of (i1,i2):
  36687. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  36688. // along i1 : lerp(x0,x1, i1/(S-i2))
  36689. //
  36690. // centroid of triangle is needed to get help normal computation
  36691. // (c1,c2) are used for centroid location
  36692. var interp_vertex = function (i1, i2, c1, c2) {
  36693. // vertex is interpolated from
  36694. // - face_vertex_pos[0..2]
  36695. // - face_vertex_uv[0..2]
  36696. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  36697. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  36698. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  36699. pos_interp.normalize();
  36700. var vertex_normal;
  36701. if (flat) {
  36702. // in flat mode, recalculate normal as face centroid normal
  36703. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  36704. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  36705. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  36706. }
  36707. else {
  36708. // in smooth mode, recalculate normal from each single vertex position
  36709. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  36710. }
  36711. // Vertex normal need correction due to X,Y,Z radius scaling
  36712. vertex_normal.x /= radiusX;
  36713. vertex_normal.y /= radiusY;
  36714. vertex_normal.z /= radiusZ;
  36715. vertex_normal.normalize();
  36716. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  36717. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  36718. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  36719. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  36720. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  36721. uvs.push(uv_interp.x, uv_interp.y);
  36722. // push each vertex has member of a face
  36723. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  36724. indices.push(current_indice);
  36725. current_indice++;
  36726. };
  36727. for (var i2 = 0; i2 < subdivisions; i2++) {
  36728. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  36729. // face : (i1,i2) for /\ :
  36730. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  36731. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  36732. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  36733. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  36734. if (i1 + i2 + 1 < subdivisions) {
  36735. // face : (i1,i2)' for \/ :
  36736. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  36737. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  36738. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  36739. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  36740. }
  36741. }
  36742. }
  36743. }
  36744. // Sides
  36745. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36746. // Result
  36747. var vertexData = new VertexData();
  36748. vertexData.indices = indices;
  36749. vertexData.positions = positions;
  36750. vertexData.normals = normals;
  36751. vertexData.uvs = uvs;
  36752. return vertexData;
  36753. };
  36754. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  36755. /**
  36756. * Creates the VertexData of the Polyhedron.
  36757. */
  36758. VertexData.CreatePolyhedron = function (options) {
  36759. // provided polyhedron types :
  36760. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  36761. // 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)
  36762. var polyhedra = [];
  36763. 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]] };
  36764. 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]] };
  36765. polyhedra[2] = {
  36766. 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]],
  36767. 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]]
  36768. };
  36769. polyhedra[3] = {
  36770. 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]],
  36771. 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]]
  36772. };
  36773. polyhedra[4] = {
  36774. 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]],
  36775. 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]]
  36776. };
  36777. 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]] };
  36778. 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]] };
  36779. 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]] };
  36780. 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]] };
  36781. 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]] };
  36782. 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]] };
  36783. 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]] };
  36784. 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]] };
  36785. 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]] };
  36786. polyhedra[14] = {
  36787. 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]],
  36788. 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]]
  36789. };
  36790. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  36791. var size = options.size;
  36792. var sizeX = options.sizeX || size || 1;
  36793. var sizeY = options.sizeY || size || 1;
  36794. var sizeZ = options.sizeZ || size || 1;
  36795. var data = options.custom || polyhedra[type];
  36796. var nbfaces = data.face.length;
  36797. var faceUV = options.faceUV || new Array(nbfaces);
  36798. var faceColors = options.faceColors;
  36799. var flat = (options.flat === undefined) ? true : options.flat;
  36800. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36801. var positions = new Array();
  36802. var indices = new Array();
  36803. var normals = new Array();
  36804. var uvs = new Array();
  36805. var colors = new Array();
  36806. var index = 0;
  36807. var faceIdx = 0; // face cursor in the array "indexes"
  36808. var indexes = new Array();
  36809. var i = 0;
  36810. var f = 0;
  36811. var u, v, ang, x, y, tmp;
  36812. // default face colors and UV if undefined
  36813. if (flat) {
  36814. for (f = 0; f < nbfaces; f++) {
  36815. if (faceColors && faceColors[f] === undefined) {
  36816. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36817. }
  36818. if (faceUV && faceUV[f] === undefined) {
  36819. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36820. }
  36821. }
  36822. }
  36823. if (!flat) {
  36824. for (i = 0; i < data.vertex.length; i++) {
  36825. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  36826. uvs.push(0, 0);
  36827. }
  36828. for (f = 0; f < nbfaces; f++) {
  36829. for (i = 0; i < data.face[f].length - 2; i++) {
  36830. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  36831. }
  36832. }
  36833. }
  36834. else {
  36835. for (f = 0; f < nbfaces; f++) {
  36836. var fl = data.face[f].length; // number of vertices of the current face
  36837. ang = 2 * Math.PI / fl;
  36838. x = 0.5 * Math.tan(ang / 2);
  36839. y = 0.5;
  36840. // positions, uvs, colors
  36841. for (i = 0; i < fl; i++) {
  36842. // positions
  36843. 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);
  36844. indexes.push(index);
  36845. index++;
  36846. // uvs
  36847. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  36848. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  36849. uvs.push(u, v);
  36850. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  36851. y = x * Math.sin(ang) + y * Math.cos(ang);
  36852. x = tmp;
  36853. // colors
  36854. if (faceColors) {
  36855. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  36856. }
  36857. }
  36858. // indices from indexes
  36859. for (i = 0; i < fl - 2; i++) {
  36860. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  36861. }
  36862. faceIdx += fl;
  36863. }
  36864. }
  36865. VertexData.ComputeNormals(positions, indices, normals);
  36866. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36867. var vertexData = new VertexData();
  36868. vertexData.positions = positions;
  36869. vertexData.indices = indices;
  36870. vertexData.normals = normals;
  36871. vertexData.uvs = uvs;
  36872. if (faceColors && flat) {
  36873. vertexData.colors = colors;
  36874. }
  36875. return vertexData;
  36876. };
  36877. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  36878. /**
  36879. * Creates the VertexData of the Torus Knot.
  36880. */
  36881. VertexData.CreateTorusKnot = function (options) {
  36882. var indices = new Array();
  36883. var positions = new Array();
  36884. var normals = new Array();
  36885. var uvs = new Array();
  36886. var radius = options.radius || 2;
  36887. var tube = options.tube || 0.5;
  36888. var radialSegments = options.radialSegments || 32;
  36889. var tubularSegments = options.tubularSegments || 32;
  36890. var p = options.p || 2;
  36891. var q = options.q || 3;
  36892. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36893. // Helper
  36894. var getPos = function (angle) {
  36895. var cu = Math.cos(angle);
  36896. var su = Math.sin(angle);
  36897. var quOverP = q / p * angle;
  36898. var cs = Math.cos(quOverP);
  36899. var tx = radius * (2 + cs) * 0.5 * cu;
  36900. var ty = radius * (2 + cs) * su * 0.5;
  36901. var tz = radius * Math.sin(quOverP) * 0.5;
  36902. return new BABYLON.Vector3(tx, ty, tz);
  36903. };
  36904. // Vertices
  36905. var i;
  36906. var j;
  36907. for (i = 0; i <= radialSegments; i++) {
  36908. var modI = i % radialSegments;
  36909. var u = modI / radialSegments * 2 * p * Math.PI;
  36910. var p1 = getPos(u);
  36911. var p2 = getPos(u + 0.01);
  36912. var tang = p2.subtract(p1);
  36913. var n = p2.add(p1);
  36914. var bitan = BABYLON.Vector3.Cross(tang, n);
  36915. n = BABYLON.Vector3.Cross(bitan, tang);
  36916. bitan.normalize();
  36917. n.normalize();
  36918. for (j = 0; j < tubularSegments; j++) {
  36919. var modJ = j % tubularSegments;
  36920. var v = modJ / tubularSegments * 2 * Math.PI;
  36921. var cx = -tube * Math.cos(v);
  36922. var cy = tube * Math.sin(v);
  36923. positions.push(p1.x + cx * n.x + cy * bitan.x);
  36924. positions.push(p1.y + cx * n.y + cy * bitan.y);
  36925. positions.push(p1.z + cx * n.z + cy * bitan.z);
  36926. uvs.push(i / radialSegments);
  36927. uvs.push(j / tubularSegments);
  36928. }
  36929. }
  36930. for (i = 0; i < radialSegments; i++) {
  36931. for (j = 0; j < tubularSegments; j++) {
  36932. var jNext = (j + 1) % tubularSegments;
  36933. var a = i * tubularSegments + j;
  36934. var b = (i + 1) * tubularSegments + j;
  36935. var c = (i + 1) * tubularSegments + jNext;
  36936. var d = i * tubularSegments + jNext;
  36937. indices.push(d);
  36938. indices.push(b);
  36939. indices.push(a);
  36940. indices.push(d);
  36941. indices.push(c);
  36942. indices.push(b);
  36943. }
  36944. }
  36945. // Normals
  36946. VertexData.ComputeNormals(positions, indices, normals);
  36947. // Sides
  36948. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36949. // Result
  36950. var vertexData = new VertexData();
  36951. vertexData.indices = indices;
  36952. vertexData.positions = positions;
  36953. vertexData.normals = normals;
  36954. vertexData.uvs = uvs;
  36955. return vertexData;
  36956. };
  36957. // Tools
  36958. /**
  36959. * @param {any} - positions (number[] or Float32Array)
  36960. * @param {any} - indices (number[] or Uint16Array)
  36961. * @param {any} - normals (number[] or Float32Array)
  36962. * options (optional) :
  36963. * facetPositions : optional array of facet positions (vector3)
  36964. * facetNormals : optional array of facet normals (vector3)
  36965. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  36966. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  36967. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  36968. * bbSize : optional bounding box size data, required for facetPartitioning computation
  36969. * bInfo : optional bounding info, required for facetPartitioning computation
  36970. * useRightHandedSystem: optional boolean to for right handed system computation
  36971. * depthSort : optional boolean to enable the facet depth sort computation
  36972. * distanceTo : optional Vector3 to compute the facet depth from this location
  36973. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  36974. */
  36975. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  36976. // temporary scalar variables
  36977. var index = 0; // facet index
  36978. var p1p2x = 0.0; // p1p2 vector x coordinate
  36979. var p1p2y = 0.0; // p1p2 vector y coordinate
  36980. var p1p2z = 0.0; // p1p2 vector z coordinate
  36981. var p3p2x = 0.0; // p3p2 vector x coordinate
  36982. var p3p2y = 0.0; // p3p2 vector y coordinate
  36983. var p3p2z = 0.0; // p3p2 vector z coordinate
  36984. var faceNormalx = 0.0; // facet normal x coordinate
  36985. var faceNormaly = 0.0; // facet normal y coordinate
  36986. var faceNormalz = 0.0; // facet normal z coordinate
  36987. var length = 0.0; // facet normal length before normalization
  36988. var v1x = 0; // vector1 x index in the positions array
  36989. var v1y = 0; // vector1 y index in the positions array
  36990. var v1z = 0; // vector1 z index in the positions array
  36991. var v2x = 0; // vector2 x index in the positions array
  36992. var v2y = 0; // vector2 y index in the positions array
  36993. var v2z = 0; // vector2 z index in the positions array
  36994. var v3x = 0; // vector3 x index in the positions array
  36995. var v3y = 0; // vector3 y index in the positions array
  36996. var v3z = 0; // vector3 z index in the positions array
  36997. var computeFacetNormals = false;
  36998. var computeFacetPositions = false;
  36999. var computeFacetPartitioning = false;
  37000. var computeDepthSort = false;
  37001. var faceNormalSign = 1;
  37002. var ratio = 0;
  37003. var distanceTo = null;
  37004. if (options) {
  37005. computeFacetNormals = (options.facetNormals) ? true : false;
  37006. computeFacetPositions = (options.facetPositions) ? true : false;
  37007. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  37008. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  37009. ratio = options.ratio || 0;
  37010. computeDepthSort = (options.depthSort) ? true : false;
  37011. distanceTo = (options.distanceTo);
  37012. if (computeDepthSort) {
  37013. if (distanceTo === undefined) {
  37014. distanceTo = BABYLON.Vector3.Zero();
  37015. }
  37016. var depthSortedFacets = options.depthSortedFacets;
  37017. }
  37018. }
  37019. // facetPartitioning reinit if needed
  37020. var xSubRatio = 0;
  37021. var ySubRatio = 0;
  37022. var zSubRatio = 0;
  37023. var subSq = 0;
  37024. if (computeFacetPartitioning && options && options.bbSize) {
  37025. var ox = 0; // X partitioning index for facet position
  37026. var oy = 0; // Y partinioning index for facet position
  37027. var oz = 0; // Z partinioning index for facet position
  37028. var b1x = 0; // X partitioning index for facet v1 vertex
  37029. var b1y = 0; // Y partitioning index for facet v1 vertex
  37030. var b1z = 0; // z partitioning index for facet v1 vertex
  37031. var b2x = 0; // X partitioning index for facet v2 vertex
  37032. var b2y = 0; // Y partitioning index for facet v2 vertex
  37033. var b2z = 0; // Z partitioning index for facet v2 vertex
  37034. var b3x = 0; // X partitioning index for facet v3 vertex
  37035. var b3y = 0; // Y partitioning index for facet v3 vertex
  37036. var b3z = 0; // Z partitioning index for facet v3 vertex
  37037. var block_idx_o = 0; // facet barycenter block index
  37038. var block_idx_v1 = 0; // v1 vertex block index
  37039. var block_idx_v2 = 0; // v2 vertex block index
  37040. var block_idx_v3 = 0; // v3 vertex block index
  37041. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  37042. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  37043. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  37044. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  37045. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  37046. subSq = options.subDiv.max * options.subDiv.max;
  37047. options.facetPartitioning.length = 0;
  37048. }
  37049. // reset the normals
  37050. for (index = 0; index < positions.length; index++) {
  37051. normals[index] = 0.0;
  37052. }
  37053. // Loop : 1 indice triplet = 1 facet
  37054. var nbFaces = (indices.length / 3) | 0;
  37055. for (index = 0; index < nbFaces; index++) {
  37056. // get the indexes of the coordinates of each vertex of the facet
  37057. v1x = indices[index * 3] * 3;
  37058. v1y = v1x + 1;
  37059. v1z = v1x + 2;
  37060. v2x = indices[index * 3 + 1] * 3;
  37061. v2y = v2x + 1;
  37062. v2z = v2x + 2;
  37063. v3x = indices[index * 3 + 2] * 3;
  37064. v3y = v3x + 1;
  37065. v3z = v3x + 2;
  37066. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  37067. p1p2y = positions[v1y] - positions[v2y];
  37068. p1p2z = positions[v1z] - positions[v2z];
  37069. p3p2x = positions[v3x] - positions[v2x];
  37070. p3p2y = positions[v3y] - positions[v2y];
  37071. p3p2z = positions[v3z] - positions[v2z];
  37072. // compute the face normal with the cross product
  37073. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  37074. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  37075. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  37076. // normalize this normal and store it in the array facetData
  37077. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  37078. length = (length === 0) ? 1.0 : length;
  37079. faceNormalx /= length;
  37080. faceNormaly /= length;
  37081. faceNormalz /= length;
  37082. if (computeFacetNormals && options) {
  37083. options.facetNormals[index].x = faceNormalx;
  37084. options.facetNormals[index].y = faceNormaly;
  37085. options.facetNormals[index].z = faceNormalz;
  37086. }
  37087. if (computeFacetPositions && options) {
  37088. // compute and the facet barycenter coordinates in the array facetPositions
  37089. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  37090. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  37091. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  37092. }
  37093. if (computeFacetPartitioning && options) {
  37094. // store the facet indexes in arrays in the main facetPartitioning array :
  37095. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  37096. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  37097. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  37098. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  37099. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  37100. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  37101. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  37102. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  37103. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  37104. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  37105. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  37106. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  37107. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  37108. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  37109. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  37110. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  37111. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  37112. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  37113. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  37114. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  37115. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  37116. // push each facet index in each block containing the vertex
  37117. options.facetPartitioning[block_idx_v1].push(index);
  37118. if (block_idx_v2 != block_idx_v1) {
  37119. options.facetPartitioning[block_idx_v2].push(index);
  37120. }
  37121. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  37122. options.facetPartitioning[block_idx_v3].push(index);
  37123. }
  37124. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  37125. options.facetPartitioning[block_idx_o].push(index);
  37126. }
  37127. }
  37128. if (computeDepthSort && options && options.facetPositions) {
  37129. var dsf = depthSortedFacets[index];
  37130. dsf.ind = index * 3;
  37131. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  37132. }
  37133. // compute the normals anyway
  37134. normals[v1x] += faceNormalx; // accumulate all the normals per face
  37135. normals[v1y] += faceNormaly;
  37136. normals[v1z] += faceNormalz;
  37137. normals[v2x] += faceNormalx;
  37138. normals[v2y] += faceNormaly;
  37139. normals[v2z] += faceNormalz;
  37140. normals[v3x] += faceNormalx;
  37141. normals[v3y] += faceNormaly;
  37142. normals[v3z] += faceNormalz;
  37143. }
  37144. // last normalization of each normal
  37145. for (index = 0; index < normals.length / 3; index++) {
  37146. faceNormalx = normals[index * 3];
  37147. faceNormaly = normals[index * 3 + 1];
  37148. faceNormalz = normals[index * 3 + 2];
  37149. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  37150. length = (length === 0) ? 1.0 : length;
  37151. faceNormalx /= length;
  37152. faceNormaly /= length;
  37153. faceNormalz /= length;
  37154. normals[index * 3] = faceNormalx;
  37155. normals[index * 3 + 1] = faceNormaly;
  37156. normals[index * 3 + 2] = faceNormalz;
  37157. }
  37158. };
  37159. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  37160. var li = indices.length;
  37161. var ln = normals.length;
  37162. var i;
  37163. var n;
  37164. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37165. switch (sideOrientation) {
  37166. case BABYLON.Mesh.FRONTSIDE:
  37167. // nothing changed
  37168. break;
  37169. case BABYLON.Mesh.BACKSIDE:
  37170. var tmp;
  37171. // indices
  37172. for (i = 0; i < li; i += 3) {
  37173. tmp = indices[i];
  37174. indices[i] = indices[i + 2];
  37175. indices[i + 2] = tmp;
  37176. }
  37177. // normals
  37178. for (n = 0; n < ln; n++) {
  37179. normals[n] = -normals[n];
  37180. }
  37181. break;
  37182. case BABYLON.Mesh.DOUBLESIDE:
  37183. // positions
  37184. var lp = positions.length;
  37185. var l = lp / 3;
  37186. for (var p = 0; p < lp; p++) {
  37187. positions[lp + p] = positions[p];
  37188. }
  37189. // indices
  37190. for (i = 0; i < li; i += 3) {
  37191. indices[i + li] = indices[i + 2] + l;
  37192. indices[i + 1 + li] = indices[i + 1] + l;
  37193. indices[i + 2 + li] = indices[i] + l;
  37194. }
  37195. // normals
  37196. for (n = 0; n < ln; n++) {
  37197. normals[ln + n] = -normals[n];
  37198. }
  37199. // uvs
  37200. var lu = uvs.length;
  37201. var u = 0;
  37202. for (u = 0; u < lu; u++) {
  37203. uvs[u + lu] = uvs[u];
  37204. }
  37205. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  37206. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  37207. u = 0;
  37208. for (i = 0; i < lu / 2; i++) {
  37209. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  37210. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  37211. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  37212. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  37213. u += 2;
  37214. }
  37215. break;
  37216. }
  37217. };
  37218. /**
  37219. * Creates a new VertexData from the imported parameters.
  37220. */
  37221. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  37222. var vertexData = new VertexData();
  37223. // positions
  37224. var positions = parsedVertexData.positions;
  37225. if (positions) {
  37226. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  37227. }
  37228. // normals
  37229. var normals = parsedVertexData.normals;
  37230. if (normals) {
  37231. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  37232. }
  37233. // tangents
  37234. var tangents = parsedVertexData.tangents;
  37235. if (tangents) {
  37236. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  37237. }
  37238. // uvs
  37239. var uvs = parsedVertexData.uvs;
  37240. if (uvs) {
  37241. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  37242. }
  37243. // uv2s
  37244. var uv2s = parsedVertexData.uv2s;
  37245. if (uv2s) {
  37246. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  37247. }
  37248. // uv3s
  37249. var uv3s = parsedVertexData.uv3s;
  37250. if (uv3s) {
  37251. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  37252. }
  37253. // uv4s
  37254. var uv4s = parsedVertexData.uv4s;
  37255. if (uv4s) {
  37256. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  37257. }
  37258. // uv5s
  37259. var uv5s = parsedVertexData.uv5s;
  37260. if (uv5s) {
  37261. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  37262. }
  37263. // uv6s
  37264. var uv6s = parsedVertexData.uv6s;
  37265. if (uv6s) {
  37266. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  37267. }
  37268. // colors
  37269. var colors = parsedVertexData.colors;
  37270. if (colors) {
  37271. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  37272. }
  37273. // matricesIndices
  37274. var matricesIndices = parsedVertexData.matricesIndices;
  37275. if (matricesIndices) {
  37276. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  37277. }
  37278. // matricesWeights
  37279. var matricesWeights = parsedVertexData.matricesWeights;
  37280. if (matricesWeights) {
  37281. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  37282. }
  37283. // indices
  37284. var indices = parsedVertexData.indices;
  37285. if (indices) {
  37286. vertexData.indices = indices;
  37287. }
  37288. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  37289. };
  37290. return VertexData;
  37291. }());
  37292. BABYLON.VertexData = VertexData;
  37293. })(BABYLON || (BABYLON = {}));
  37294. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  37295. "use strict";
  37296. var BABYLON;
  37297. (function (BABYLON) {
  37298. /**
  37299. * Class used to store geometry data (vertex buffers + index buffer)
  37300. */
  37301. var Geometry = /** @class */ (function () {
  37302. /**
  37303. * Creates a new geometry
  37304. * @param id defines the unique ID
  37305. * @param scene defines the hosting scene
  37306. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  37307. * @param updatable defines if geometry must be updatable (false by default)
  37308. * @param mesh defines the mesh that will be associated with the geometry
  37309. */
  37310. function Geometry(id, scene, vertexData, updatable, mesh) {
  37311. if (updatable === void 0) { updatable = false; }
  37312. if (mesh === void 0) { mesh = null; }
  37313. /**
  37314. * Gets the delay loading state of the geometry (none by default which means not delayed)
  37315. */
  37316. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  37317. this._totalVertices = 0;
  37318. this._isDisposed = false;
  37319. this._indexBufferIsUpdatable = false;
  37320. this.id = id;
  37321. this._engine = scene.getEngine();
  37322. this._meshes = [];
  37323. this._scene = scene;
  37324. //Init vertex buffer cache
  37325. this._vertexBuffers = {};
  37326. this._indices = [];
  37327. this._updatable = updatable;
  37328. // vertexData
  37329. if (vertexData) {
  37330. this.setAllVerticesData(vertexData, updatable);
  37331. }
  37332. else {
  37333. this._totalVertices = 0;
  37334. this._indices = [];
  37335. }
  37336. if (this._engine.getCaps().vertexArrayObject) {
  37337. this._vertexArrayObjects = {};
  37338. }
  37339. // applyToMesh
  37340. if (mesh) {
  37341. if (mesh.getClassName() === "LinesMesh") {
  37342. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  37343. this._updateExtend();
  37344. }
  37345. this.applyToMesh(mesh);
  37346. mesh.computeWorldMatrix(true);
  37347. }
  37348. }
  37349. Object.defineProperty(Geometry.prototype, "boundingBias", {
  37350. /**
  37351. * 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
  37352. */
  37353. get: function () {
  37354. return this._boundingBias;
  37355. },
  37356. /**
  37357. * 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
  37358. */
  37359. set: function (value) {
  37360. if (this._boundingBias && this._boundingBias.equals(value)) {
  37361. return;
  37362. }
  37363. this._boundingBias = value.clone();
  37364. this._updateBoundingInfo(true, null);
  37365. },
  37366. enumerable: true,
  37367. configurable: true
  37368. });
  37369. /**
  37370. * Static function used to attach a new empty geometry to a mesh
  37371. * @param mesh defines the mesh to attach the geometry to
  37372. * @returns the new {BABYLON.Geometry}
  37373. */
  37374. Geometry.CreateGeometryForMesh = function (mesh) {
  37375. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  37376. geometry.applyToMesh(mesh);
  37377. return geometry;
  37378. };
  37379. Object.defineProperty(Geometry.prototype, "extend", {
  37380. /**
  37381. * Gets the current extend of the geometry
  37382. */
  37383. get: function () {
  37384. return this._extend;
  37385. },
  37386. enumerable: true,
  37387. configurable: true
  37388. });
  37389. /**
  37390. * Gets the hosting scene
  37391. * @returns the hosting {BABYLON.Scene}
  37392. */
  37393. Geometry.prototype.getScene = function () {
  37394. return this._scene;
  37395. };
  37396. /**
  37397. * Gets the hosting engine
  37398. * @returns the hosting {BABYLON.Engine}
  37399. */
  37400. Geometry.prototype.getEngine = function () {
  37401. return this._engine;
  37402. };
  37403. /**
  37404. * Defines if the geometry is ready to use
  37405. * @returns true if the geometry is ready to be used
  37406. */
  37407. Geometry.prototype.isReady = function () {
  37408. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  37409. };
  37410. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  37411. /**
  37412. * Gets a value indicating that the geometry should not be serialized
  37413. */
  37414. get: function () {
  37415. for (var index = 0; index < this._meshes.length; index++) {
  37416. if (!this._meshes[index].doNotSerialize) {
  37417. return false;
  37418. }
  37419. }
  37420. return true;
  37421. },
  37422. enumerable: true,
  37423. configurable: true
  37424. });
  37425. /** @ignore */
  37426. Geometry.prototype._rebuild = function () {
  37427. if (this._vertexArrayObjects) {
  37428. this._vertexArrayObjects = {};
  37429. }
  37430. // Index buffer
  37431. if (this._meshes.length !== 0 && this._indices) {
  37432. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  37433. }
  37434. // Vertex buffers
  37435. for (var key in this._vertexBuffers) {
  37436. var vertexBuffer = this._vertexBuffers[key];
  37437. vertexBuffer._rebuild();
  37438. }
  37439. };
  37440. /**
  37441. * Affects all gemetry data in one call
  37442. * @param vertexData defines the geometry data
  37443. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  37444. */
  37445. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  37446. vertexData.applyToGeometry(this, updatable);
  37447. this.notifyUpdate();
  37448. };
  37449. /**
  37450. * Set specific vertex data
  37451. * @param kind defines the data kind (Position, normal, etc...)
  37452. * @param data defines the vertex data to use
  37453. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  37454. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  37455. */
  37456. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  37457. if (updatable === void 0) { updatable = false; }
  37458. if (kind === BABYLON.VertexBuffer.PositionKind) {
  37459. this._totalVertices = data.length / (stride || 3);
  37460. }
  37461. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  37462. this.setVerticesBuffer(buffer);
  37463. };
  37464. /**
  37465. * Removes a specific vertex data
  37466. * @param kind defines the data kind (Position, normal, etc...)
  37467. */
  37468. Geometry.prototype.removeVerticesData = function (kind) {
  37469. if (this._vertexBuffers[kind]) {
  37470. this._vertexBuffers[kind].dispose();
  37471. delete this._vertexBuffers[kind];
  37472. }
  37473. };
  37474. /**
  37475. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  37476. * @param buffer defines the vertex buffer to use
  37477. * @param totalVertices defines the total number of vertices for position kind (could be null)
  37478. */
  37479. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  37480. if (totalVertices === void 0) { totalVertices = null; }
  37481. var kind = buffer.getKind();
  37482. if (this._vertexBuffers[kind]) {
  37483. this._vertexBuffers[kind].dispose();
  37484. }
  37485. this._vertexBuffers[kind] = buffer;
  37486. if (kind === BABYLON.VertexBuffer.PositionKind) {
  37487. if (totalVertices != null) {
  37488. this._totalVertices = totalVertices;
  37489. }
  37490. this._updateExtend();
  37491. this._resetPointsArrayCache();
  37492. var meshes = this._meshes;
  37493. var numOfMeshes = meshes.length;
  37494. for (var index = 0; index < numOfMeshes; index++) {
  37495. var mesh = meshes[index];
  37496. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  37497. mesh._createGlobalSubMesh(false);
  37498. mesh.computeWorldMatrix(true);
  37499. }
  37500. }
  37501. this.notifyUpdate(kind);
  37502. if (this._vertexArrayObjects) {
  37503. this._disposeVertexArrayObjects();
  37504. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  37505. }
  37506. };
  37507. /**
  37508. * Update a specific vertex buffer
  37509. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  37510. * It will do nothing if the buffer is not updatable
  37511. * @param kind defines the data kind (Position, normal, etc...)
  37512. * @param data defines the data to use
  37513. * @param offset defines the offset in the target buffer where to store the data
  37514. */
  37515. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  37516. var vertexBuffer = this.getVertexBuffer(kind);
  37517. if (!vertexBuffer) {
  37518. return;
  37519. }
  37520. vertexBuffer.updateDirectly(data, offset);
  37521. this.notifyUpdate(kind);
  37522. };
  37523. /**
  37524. * Update a specific vertex buffer
  37525. * This function will create a new buffer if the current one is not updatable
  37526. * @param kind defines the data kind (Position, normal, etc...)
  37527. * @param data defines the data to use
  37528. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  37529. */
  37530. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  37531. if (updateExtends === void 0) { updateExtends = false; }
  37532. var vertexBuffer = this.getVertexBuffer(kind);
  37533. if (!vertexBuffer) {
  37534. return;
  37535. }
  37536. vertexBuffer.update(data);
  37537. if (kind === BABYLON.VertexBuffer.PositionKind) {
  37538. this._updateBoundingInfo(updateExtends, data);
  37539. }
  37540. this.notifyUpdate(kind);
  37541. };
  37542. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  37543. if (updateExtends) {
  37544. this._updateExtend(data);
  37545. }
  37546. var meshes = this._meshes;
  37547. var numOfMeshes = meshes.length;
  37548. this._resetPointsArrayCache();
  37549. for (var index = 0; index < numOfMeshes; index++) {
  37550. var mesh = meshes[index];
  37551. if (updateExtends) {
  37552. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  37553. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  37554. var subMesh = mesh.subMeshes[subIndex];
  37555. subMesh.refreshBoundingInfo();
  37556. }
  37557. }
  37558. }
  37559. };
  37560. /** @ignore */
  37561. Geometry.prototype._bind = function (effect, indexToBind) {
  37562. if (!effect) {
  37563. return;
  37564. }
  37565. if (indexToBind === undefined) {
  37566. indexToBind = this._indexBuffer;
  37567. }
  37568. var vbs = this.getVertexBuffers();
  37569. if (!vbs) {
  37570. return;
  37571. }
  37572. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  37573. this._engine.bindBuffers(vbs, indexToBind, effect);
  37574. return;
  37575. }
  37576. // Using VAO
  37577. if (!this._vertexArrayObjects[effect.key]) {
  37578. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  37579. }
  37580. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  37581. };
  37582. /**
  37583. * Gets total number of vertices
  37584. * @returns the total number of vertices
  37585. */
  37586. Geometry.prototype.getTotalVertices = function () {
  37587. if (!this.isReady()) {
  37588. return 0;
  37589. }
  37590. return this._totalVertices;
  37591. };
  37592. /**
  37593. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  37594. * @param kind defines the data kind (Position, normal, etc...)
  37595. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  37596. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  37597. * @returns a float array containing vertex data
  37598. */
  37599. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  37600. var vertexBuffer = this.getVertexBuffer(kind);
  37601. if (!vertexBuffer) {
  37602. return null;
  37603. }
  37604. var data = vertexBuffer.getData();
  37605. if (!data) {
  37606. return null;
  37607. }
  37608. var defaultStride = BABYLON.VertexBuffer.DeduceStride(vertexBuffer.getKind());
  37609. var defaultByteStride = defaultStride * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  37610. var count = this._totalVertices * defaultStride;
  37611. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== defaultByteStride) {
  37612. var copy_1 = new Array(count);
  37613. vertexBuffer.forEach(count, function (value, index) {
  37614. copy_1[index] = value;
  37615. });
  37616. return copy_1;
  37617. }
  37618. if (!(data instanceof Array || data instanceof Float32Array) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  37619. if (data instanceof Array) {
  37620. var offset = vertexBuffer.byteOffset / 4;
  37621. return BABYLON.Tools.Slice(data, offset, offset + count);
  37622. }
  37623. else if (data instanceof ArrayBuffer) {
  37624. return new Float32Array(data, vertexBuffer.byteOffset, count);
  37625. }
  37626. else {
  37627. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  37628. }
  37629. }
  37630. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  37631. return BABYLON.Tools.Slice(data);
  37632. }
  37633. return data;
  37634. };
  37635. /**
  37636. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  37637. * @param kind defines the data kind (Position, normal, etc...)
  37638. * @returns true if the vertex buffer with the specified kind is updatable
  37639. */
  37640. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  37641. var vb = this._vertexBuffers[kind];
  37642. if (!vb) {
  37643. return false;
  37644. }
  37645. return vb.isUpdatable();
  37646. };
  37647. /**
  37648. * Gets a specific vertex buffer
  37649. * @param kind defines the data kind (Position, normal, etc...)
  37650. * @returns a {BABYLON.VertexBuffer}
  37651. */
  37652. Geometry.prototype.getVertexBuffer = function (kind) {
  37653. if (!this.isReady()) {
  37654. return null;
  37655. }
  37656. return this._vertexBuffers[kind];
  37657. };
  37658. /**
  37659. * Returns all vertex buffers
  37660. * @return an object holding all vertex buffers indexed by kind
  37661. */
  37662. Geometry.prototype.getVertexBuffers = function () {
  37663. if (!this.isReady()) {
  37664. return null;
  37665. }
  37666. return this._vertexBuffers;
  37667. };
  37668. /**
  37669. * Gets a boolean indicating if specific vertex buffer is present
  37670. * @param kind defines the data kind (Position, normal, etc...)
  37671. * @returns true if data is present
  37672. */
  37673. Geometry.prototype.isVerticesDataPresent = function (kind) {
  37674. if (!this._vertexBuffers) {
  37675. if (this._delayInfo) {
  37676. return this._delayInfo.indexOf(kind) !== -1;
  37677. }
  37678. return false;
  37679. }
  37680. return this._vertexBuffers[kind] !== undefined;
  37681. };
  37682. /**
  37683. * Gets a list of all attached data kinds (Position, normal, etc...)
  37684. * @returns a list of string containing all kinds
  37685. */
  37686. Geometry.prototype.getVerticesDataKinds = function () {
  37687. var result = [];
  37688. var kind;
  37689. if (!this._vertexBuffers && this._delayInfo) {
  37690. for (kind in this._delayInfo) {
  37691. result.push(kind);
  37692. }
  37693. }
  37694. else {
  37695. for (kind in this._vertexBuffers) {
  37696. result.push(kind);
  37697. }
  37698. }
  37699. return result;
  37700. };
  37701. /**
  37702. * Update index buffer
  37703. * @param indices defines the indices to store in the index buffer
  37704. * @param offset defines the offset in the target buffer where to store the data
  37705. */
  37706. Geometry.prototype.updateIndices = function (indices, offset) {
  37707. if (!this._indexBuffer) {
  37708. return;
  37709. }
  37710. if (!this._indexBufferIsUpdatable) {
  37711. this.setIndices(indices, null, true);
  37712. }
  37713. else {
  37714. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  37715. }
  37716. };
  37717. /**
  37718. * Creates a new index buffer
  37719. * @param indices defines the indices to store in the index buffer
  37720. * @param totalVertices defines the total number of vertices (could be null)
  37721. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  37722. */
  37723. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  37724. if (totalVertices === void 0) { totalVertices = null; }
  37725. if (updatable === void 0) { updatable = false; }
  37726. if (this._indexBuffer) {
  37727. this._engine._releaseBuffer(this._indexBuffer);
  37728. }
  37729. this._disposeVertexArrayObjects();
  37730. this._indices = indices;
  37731. this._indexBufferIsUpdatable = updatable;
  37732. if (this._meshes.length !== 0 && this._indices) {
  37733. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  37734. }
  37735. if (totalVertices != undefined) {
  37736. this._totalVertices = totalVertices;
  37737. }
  37738. var meshes = this._meshes;
  37739. var numOfMeshes = meshes.length;
  37740. for (var index = 0; index < numOfMeshes; index++) {
  37741. meshes[index]._createGlobalSubMesh(true);
  37742. }
  37743. this.notifyUpdate();
  37744. };
  37745. /**
  37746. * Return the total number of indices
  37747. * @returns the total number of indices
  37748. */
  37749. Geometry.prototype.getTotalIndices = function () {
  37750. if (!this.isReady()) {
  37751. return 0;
  37752. }
  37753. return this._indices.length;
  37754. };
  37755. /**
  37756. * Gets the index buffer array
  37757. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  37758. * @returns the index buffer array
  37759. */
  37760. Geometry.prototype.getIndices = function (copyWhenShared) {
  37761. if (!this.isReady()) {
  37762. return null;
  37763. }
  37764. var orig = this._indices;
  37765. if (!copyWhenShared || this._meshes.length === 1) {
  37766. return orig;
  37767. }
  37768. else {
  37769. var len = orig.length;
  37770. var copy = [];
  37771. for (var i = 0; i < len; i++) {
  37772. copy.push(orig[i]);
  37773. }
  37774. return copy;
  37775. }
  37776. };
  37777. /**
  37778. * Gets the index buffer
  37779. * @return the index buffer
  37780. */
  37781. Geometry.prototype.getIndexBuffer = function () {
  37782. if (!this.isReady()) {
  37783. return null;
  37784. }
  37785. return this._indexBuffer;
  37786. };
  37787. /** @ignore */
  37788. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  37789. if (effect === void 0) { effect = null; }
  37790. if (!effect || !this._vertexArrayObjects) {
  37791. return;
  37792. }
  37793. if (this._vertexArrayObjects[effect.key]) {
  37794. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  37795. delete this._vertexArrayObjects[effect.key];
  37796. }
  37797. };
  37798. /**
  37799. * Release the associated resources for a specific mesh
  37800. * @param mesh defines the source mesh
  37801. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  37802. */
  37803. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  37804. var meshes = this._meshes;
  37805. var index = meshes.indexOf(mesh);
  37806. if (index === -1) {
  37807. return;
  37808. }
  37809. meshes.splice(index, 1);
  37810. mesh._geometry = null;
  37811. if (meshes.length === 0 && shouldDispose) {
  37812. this.dispose();
  37813. }
  37814. };
  37815. /**
  37816. * Apply current geometry to a given mesh
  37817. * @param mesh defines the mesh to apply geometry to
  37818. */
  37819. Geometry.prototype.applyToMesh = function (mesh) {
  37820. if (mesh._geometry === this) {
  37821. return;
  37822. }
  37823. var previousGeometry = mesh._geometry;
  37824. if (previousGeometry) {
  37825. previousGeometry.releaseForMesh(mesh);
  37826. }
  37827. var meshes = this._meshes;
  37828. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  37829. mesh._geometry = this;
  37830. this._scene.pushGeometry(this);
  37831. meshes.push(mesh);
  37832. if (this.isReady()) {
  37833. this._applyToMesh(mesh);
  37834. }
  37835. else {
  37836. mesh._boundingInfo = this._boundingInfo;
  37837. }
  37838. };
  37839. Geometry.prototype._updateExtend = function (data) {
  37840. if (data === void 0) { data = null; }
  37841. if (!data) {
  37842. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37843. }
  37844. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  37845. };
  37846. Geometry.prototype._applyToMesh = function (mesh) {
  37847. var numOfMeshes = this._meshes.length;
  37848. // vertexBuffers
  37849. for (var kind in this._vertexBuffers) {
  37850. if (numOfMeshes === 1) {
  37851. this._vertexBuffers[kind].create();
  37852. }
  37853. var buffer = this._vertexBuffers[kind].getBuffer();
  37854. if (buffer)
  37855. buffer.references = numOfMeshes;
  37856. if (kind === BABYLON.VertexBuffer.PositionKind) {
  37857. if (!this._extend) {
  37858. this._updateExtend();
  37859. }
  37860. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  37861. mesh._createGlobalSubMesh(false);
  37862. //bounding info was just created again, world matrix should be applied again.
  37863. mesh._updateBoundingInfo();
  37864. }
  37865. }
  37866. // indexBuffer
  37867. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  37868. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  37869. }
  37870. if (this._indexBuffer) {
  37871. this._indexBuffer.references = numOfMeshes;
  37872. }
  37873. };
  37874. Geometry.prototype.notifyUpdate = function (kind) {
  37875. if (this.onGeometryUpdated) {
  37876. this.onGeometryUpdated(this, kind);
  37877. }
  37878. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  37879. var mesh = _a[_i];
  37880. mesh._markSubMeshesAsAttributesDirty();
  37881. }
  37882. };
  37883. /**
  37884. * Load the geometry if it was flagged as delay loaded
  37885. * @param scene defines the hosting scene
  37886. * @param onLoaded defines a callback called when the geometry is loaded
  37887. */
  37888. Geometry.prototype.load = function (scene, onLoaded) {
  37889. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  37890. return;
  37891. }
  37892. if (this.isReady()) {
  37893. if (onLoaded) {
  37894. onLoaded();
  37895. }
  37896. return;
  37897. }
  37898. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  37899. this._queueLoad(scene, onLoaded);
  37900. };
  37901. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  37902. var _this = this;
  37903. if (!this.delayLoadingFile) {
  37904. return;
  37905. }
  37906. scene._addPendingData(this);
  37907. scene._loadFile(this.delayLoadingFile, function (data) {
  37908. if (!_this._delayLoadingFunction) {
  37909. return;
  37910. }
  37911. _this._delayLoadingFunction(JSON.parse(data), _this);
  37912. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  37913. _this._delayInfo = [];
  37914. scene._removePendingData(_this);
  37915. var meshes = _this._meshes;
  37916. var numOfMeshes = meshes.length;
  37917. for (var index = 0; index < numOfMeshes; index++) {
  37918. _this._applyToMesh(meshes[index]);
  37919. }
  37920. if (onLoaded) {
  37921. onLoaded();
  37922. }
  37923. }, undefined, true);
  37924. };
  37925. /**
  37926. * Invert the geometry to move from a right handed system to a left handed one.
  37927. */
  37928. Geometry.prototype.toLeftHanded = function () {
  37929. // Flip faces
  37930. var tIndices = this.getIndices(false);
  37931. if (tIndices != null && tIndices.length > 0) {
  37932. for (var i = 0; i < tIndices.length; i += 3) {
  37933. var tTemp = tIndices[i + 0];
  37934. tIndices[i + 0] = tIndices[i + 2];
  37935. tIndices[i + 2] = tTemp;
  37936. }
  37937. this.setIndices(tIndices);
  37938. }
  37939. // Negate position.z
  37940. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  37941. if (tPositions != null && tPositions.length > 0) {
  37942. for (var i = 0; i < tPositions.length; i += 3) {
  37943. tPositions[i + 2] = -tPositions[i + 2];
  37944. }
  37945. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  37946. }
  37947. // Negate normal.z
  37948. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  37949. if (tNormals != null && tNormals.length > 0) {
  37950. for (var i = 0; i < tNormals.length; i += 3) {
  37951. tNormals[i + 2] = -tNormals[i + 2];
  37952. }
  37953. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  37954. }
  37955. };
  37956. // Cache
  37957. /** @ignore */
  37958. Geometry.prototype._resetPointsArrayCache = function () {
  37959. this._positions = null;
  37960. };
  37961. /** @ignore */
  37962. Geometry.prototype._generatePointsArray = function () {
  37963. if (this._positions)
  37964. return true;
  37965. this._positions = [];
  37966. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37967. if (!data) {
  37968. return false;
  37969. }
  37970. for (var index = 0; index < data.length; index += 3) {
  37971. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  37972. }
  37973. return true;
  37974. };
  37975. /**
  37976. * Gets a value indicating if the geometry is disposed
  37977. * @returns true if the geometry was disposed
  37978. */
  37979. Geometry.prototype.isDisposed = function () {
  37980. return this._isDisposed;
  37981. };
  37982. Geometry.prototype._disposeVertexArrayObjects = function () {
  37983. if (this._vertexArrayObjects) {
  37984. for (var kind in this._vertexArrayObjects) {
  37985. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  37986. }
  37987. this._vertexArrayObjects = {};
  37988. }
  37989. };
  37990. /**
  37991. * Free all associated resources
  37992. */
  37993. Geometry.prototype.dispose = function () {
  37994. var meshes = this._meshes;
  37995. var numOfMeshes = meshes.length;
  37996. var index;
  37997. for (index = 0; index < numOfMeshes; index++) {
  37998. this.releaseForMesh(meshes[index]);
  37999. }
  38000. this._meshes = [];
  38001. this._disposeVertexArrayObjects();
  38002. for (var kind in this._vertexBuffers) {
  38003. this._vertexBuffers[kind].dispose();
  38004. }
  38005. this._vertexBuffers = {};
  38006. this._totalVertices = 0;
  38007. if (this._indexBuffer) {
  38008. this._engine._releaseBuffer(this._indexBuffer);
  38009. }
  38010. this._indexBuffer = null;
  38011. this._indices = [];
  38012. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38013. this.delayLoadingFile = null;
  38014. this._delayLoadingFunction = null;
  38015. this._delayInfo = [];
  38016. this._boundingInfo = null;
  38017. this._scene.removeGeometry(this);
  38018. this._isDisposed = true;
  38019. };
  38020. /**
  38021. * Clone the current geometry into a new geometry
  38022. * @param id defines the unique ID of the new geometry
  38023. * @returns a new geometry object
  38024. */
  38025. Geometry.prototype.copy = function (id) {
  38026. var vertexData = new BABYLON.VertexData();
  38027. vertexData.indices = [];
  38028. var indices = this.getIndices();
  38029. if (indices) {
  38030. for (var index = 0; index < indices.length; index++) {
  38031. vertexData.indices.push(indices[index]);
  38032. }
  38033. }
  38034. var updatable = false;
  38035. var stopChecking = false;
  38036. var kind;
  38037. for (kind in this._vertexBuffers) {
  38038. // using slice() to make a copy of the array and not just reference it
  38039. var data = this.getVerticesData(kind);
  38040. if (data instanceof Float32Array) {
  38041. vertexData.set(new Float32Array(data), kind);
  38042. }
  38043. else {
  38044. vertexData.set(data.slice(0), kind);
  38045. }
  38046. if (!stopChecking) {
  38047. var vb = this.getVertexBuffer(kind);
  38048. if (vb) {
  38049. updatable = vb.isUpdatable();
  38050. stopChecking = !updatable;
  38051. }
  38052. }
  38053. }
  38054. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  38055. geometry.delayLoadState = this.delayLoadState;
  38056. geometry.delayLoadingFile = this.delayLoadingFile;
  38057. geometry._delayLoadingFunction = this._delayLoadingFunction;
  38058. for (kind in this._delayInfo) {
  38059. geometry._delayInfo = geometry._delayInfo || [];
  38060. geometry._delayInfo.push(kind);
  38061. }
  38062. // Bounding info
  38063. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38064. return geometry;
  38065. };
  38066. /**
  38067. * Serialize the current geometry info (and not the vertices data) into a JSON object
  38068. * @return a JSON representation of the current geometry data (without the vertices data)
  38069. */
  38070. Geometry.prototype.serialize = function () {
  38071. var serializationObject = {};
  38072. serializationObject.id = this.id;
  38073. serializationObject.updatable = this._updatable;
  38074. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  38075. serializationObject.tags = BABYLON.Tags.GetTags(this);
  38076. }
  38077. return serializationObject;
  38078. };
  38079. Geometry.prototype.toNumberArray = function (origin) {
  38080. if (Array.isArray(origin)) {
  38081. return origin;
  38082. }
  38083. else {
  38084. return Array.prototype.slice.call(origin);
  38085. }
  38086. };
  38087. /**
  38088. * Serialize all vertices data into a JSON oject
  38089. * @returns a JSON representation of the current geometry data
  38090. */
  38091. Geometry.prototype.serializeVerticeData = function () {
  38092. var serializationObject = this.serialize();
  38093. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  38094. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  38095. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  38096. serializationObject.positions._updatable = true;
  38097. }
  38098. }
  38099. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  38100. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  38101. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  38102. serializationObject.normals._updatable = true;
  38103. }
  38104. }
  38105. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38106. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  38107. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  38108. serializationObject.tangets._updatable = true;
  38109. }
  38110. }
  38111. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38112. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  38113. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  38114. serializationObject.uvs._updatable = true;
  38115. }
  38116. }
  38117. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  38118. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  38119. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  38120. serializationObject.uv2s._updatable = true;
  38121. }
  38122. }
  38123. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  38124. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  38125. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  38126. serializationObject.uv3s._updatable = true;
  38127. }
  38128. }
  38129. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  38130. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  38131. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  38132. serializationObject.uv4s._updatable = true;
  38133. }
  38134. }
  38135. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  38136. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  38137. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  38138. serializationObject.uv5s._updatable = true;
  38139. }
  38140. }
  38141. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  38142. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  38143. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  38144. serializationObject.uv6s._updatable = true;
  38145. }
  38146. }
  38147. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  38148. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  38149. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  38150. serializationObject.colors._updatable = true;
  38151. }
  38152. }
  38153. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  38154. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  38155. serializationObject.matricesIndices._isExpanded = true;
  38156. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  38157. serializationObject.matricesIndices._updatable = true;
  38158. }
  38159. }
  38160. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  38161. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  38162. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  38163. serializationObject.matricesWeights._updatable = true;
  38164. }
  38165. }
  38166. serializationObject.indices = this.toNumberArray(this.getIndices());
  38167. return serializationObject;
  38168. };
  38169. // Statics
  38170. /**
  38171. * Extracts a clone of a mesh geometry
  38172. * @param mesh defines the source mesh
  38173. * @param id defines the unique ID of the new geometry object
  38174. * @returns the new geometry object
  38175. */
  38176. Geometry.ExtractFromMesh = function (mesh, id) {
  38177. var geometry = mesh._geometry;
  38178. if (!geometry) {
  38179. return null;
  38180. }
  38181. return geometry.copy(id);
  38182. };
  38183. /**
  38184. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  38185. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  38186. * Be aware Math.random() could cause collisions, but:
  38187. * "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"
  38188. * @returns a string containing a new GUID
  38189. */
  38190. Geometry.RandomId = function () {
  38191. return BABYLON.Tools.RandomId();
  38192. };
  38193. /** @ignore */
  38194. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  38195. var scene = mesh.getScene();
  38196. // Geometry
  38197. var geometryId = parsedGeometry.geometryId;
  38198. if (geometryId) {
  38199. var geometry = scene.getGeometryByID(geometryId);
  38200. if (geometry) {
  38201. geometry.applyToMesh(mesh);
  38202. }
  38203. }
  38204. else if (parsedGeometry instanceof ArrayBuffer) {
  38205. var binaryInfo = mesh._binaryInfo;
  38206. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  38207. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  38208. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  38209. }
  38210. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  38211. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  38212. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  38213. }
  38214. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  38215. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  38216. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  38217. }
  38218. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  38219. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  38220. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  38221. }
  38222. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  38223. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  38224. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  38225. }
  38226. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  38227. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  38228. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  38229. }
  38230. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  38231. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  38232. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  38233. }
  38234. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  38235. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  38236. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  38237. }
  38238. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  38239. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  38240. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  38241. }
  38242. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  38243. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  38244. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  38245. }
  38246. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  38247. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  38248. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  38249. }
  38250. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  38251. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  38252. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  38253. }
  38254. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  38255. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  38256. mesh.setIndices(indicesData, null);
  38257. }
  38258. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  38259. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  38260. mesh.subMeshes = [];
  38261. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  38262. var materialIndex = subMeshesData[(i * 5) + 0];
  38263. var verticesStart = subMeshesData[(i * 5) + 1];
  38264. var verticesCount = subMeshesData[(i * 5) + 2];
  38265. var indexStart = subMeshesData[(i * 5) + 3];
  38266. var indexCount = subMeshesData[(i * 5) + 4];
  38267. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  38268. }
  38269. }
  38270. }
  38271. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  38272. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  38273. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  38274. if (parsedGeometry.tangents) {
  38275. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  38276. }
  38277. if (parsedGeometry.uvs) {
  38278. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  38279. }
  38280. if (parsedGeometry.uvs2) {
  38281. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  38282. }
  38283. if (parsedGeometry.uvs3) {
  38284. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  38285. }
  38286. if (parsedGeometry.uvs4) {
  38287. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  38288. }
  38289. if (parsedGeometry.uvs5) {
  38290. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  38291. }
  38292. if (parsedGeometry.uvs6) {
  38293. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  38294. }
  38295. if (parsedGeometry.colors) {
  38296. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  38297. }
  38298. if (parsedGeometry.matricesIndices) {
  38299. if (!parsedGeometry.matricesIndices._isExpanded) {
  38300. var floatIndices = [];
  38301. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  38302. var matricesIndex = parsedGeometry.matricesIndices[i];
  38303. floatIndices.push(matricesIndex & 0x000000FF);
  38304. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  38305. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  38306. floatIndices.push(matricesIndex >> 24);
  38307. }
  38308. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  38309. }
  38310. else {
  38311. delete parsedGeometry.matricesIndices._isExpanded;
  38312. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  38313. }
  38314. }
  38315. if (parsedGeometry.matricesIndicesExtra) {
  38316. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  38317. var floatIndices = [];
  38318. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  38319. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  38320. floatIndices.push(matricesIndex & 0x000000FF);
  38321. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  38322. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  38323. floatIndices.push(matricesIndex >> 24);
  38324. }
  38325. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  38326. }
  38327. else {
  38328. delete parsedGeometry.matricesIndices._isExpanded;
  38329. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  38330. }
  38331. }
  38332. if (parsedGeometry.matricesWeights) {
  38333. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  38334. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  38335. }
  38336. if (parsedGeometry.matricesWeightsExtra) {
  38337. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  38338. }
  38339. mesh.setIndices(parsedGeometry.indices, null);
  38340. }
  38341. // SubMeshes
  38342. if (parsedGeometry.subMeshes) {
  38343. mesh.subMeshes = [];
  38344. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  38345. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  38346. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  38347. }
  38348. }
  38349. // Flat shading
  38350. if (mesh._shouldGenerateFlatShading) {
  38351. mesh.convertToFlatShadedMesh();
  38352. delete mesh._shouldGenerateFlatShading;
  38353. }
  38354. // Update
  38355. mesh.computeWorldMatrix(true);
  38356. // Octree
  38357. var sceneOctree = scene.selectionOctree;
  38358. if (sceneOctree !== undefined && sceneOctree !== null) {
  38359. sceneOctree.addMesh(mesh);
  38360. }
  38361. };
  38362. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  38363. var epsilon = 1e-3;
  38364. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  38365. return;
  38366. }
  38367. var noInfluenceBoneIndex = 0.0;
  38368. if (parsedGeometry.skeletonId > -1) {
  38369. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  38370. if (!skeleton) {
  38371. return;
  38372. }
  38373. noInfluenceBoneIndex = skeleton.bones.length;
  38374. }
  38375. else {
  38376. return;
  38377. }
  38378. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  38379. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38380. var matricesWeights = parsedGeometry.matricesWeights;
  38381. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  38382. var influencers = parsedGeometry.numBoneInfluencer;
  38383. var size = matricesWeights.length;
  38384. for (var i = 0; i < size; i += 4) {
  38385. var weight = 0.0;
  38386. var firstZeroWeight = -1;
  38387. for (var j = 0; j < 4; j++) {
  38388. var w = matricesWeights[i + j];
  38389. weight += w;
  38390. if (w < epsilon && firstZeroWeight < 0) {
  38391. firstZeroWeight = j;
  38392. }
  38393. }
  38394. if (matricesWeightsExtra) {
  38395. for (var j = 0; j < 4; j++) {
  38396. var w = matricesWeightsExtra[i + j];
  38397. weight += w;
  38398. if (w < epsilon && firstZeroWeight < 0) {
  38399. firstZeroWeight = j + 4;
  38400. }
  38401. }
  38402. }
  38403. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  38404. firstZeroWeight = influencers - 1;
  38405. }
  38406. if (weight > epsilon) {
  38407. var mweight = 1.0 / weight;
  38408. for (var j = 0; j < 4; j++) {
  38409. matricesWeights[i + j] *= mweight;
  38410. }
  38411. if (matricesWeightsExtra) {
  38412. for (var j = 0; j < 4; j++) {
  38413. matricesWeightsExtra[i + j] *= mweight;
  38414. }
  38415. }
  38416. }
  38417. else {
  38418. if (firstZeroWeight >= 4) {
  38419. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  38420. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  38421. }
  38422. else {
  38423. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  38424. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  38425. }
  38426. }
  38427. }
  38428. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  38429. if (parsedGeometry.matricesWeightsExtra) {
  38430. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  38431. }
  38432. };
  38433. /**
  38434. * Create a new geometry from persisted data (Using .babylon file format)
  38435. * @param parsedVertexData defines the persisted data
  38436. * @param scene defines the hosting scene
  38437. * @param rootUrl defines the root url to use to load assets (like delayed data)
  38438. * @returns the new geometry object
  38439. */
  38440. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  38441. if (scene.getGeometryByID(parsedVertexData.id)) {
  38442. return null; // null since geometry could be something else than a box...
  38443. }
  38444. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  38445. if (BABYLON.Tags) {
  38446. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  38447. }
  38448. if (parsedVertexData.delayLoadingFile) {
  38449. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  38450. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  38451. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  38452. geometry._delayInfo = [];
  38453. if (parsedVertexData.hasUVs) {
  38454. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  38455. }
  38456. if (parsedVertexData.hasUVs2) {
  38457. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  38458. }
  38459. if (parsedVertexData.hasUVs3) {
  38460. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  38461. }
  38462. if (parsedVertexData.hasUVs4) {
  38463. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  38464. }
  38465. if (parsedVertexData.hasUVs5) {
  38466. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  38467. }
  38468. if (parsedVertexData.hasUVs6) {
  38469. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  38470. }
  38471. if (parsedVertexData.hasColors) {
  38472. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  38473. }
  38474. if (parsedVertexData.hasMatricesIndices) {
  38475. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38476. }
  38477. if (parsedVertexData.hasMatricesWeights) {
  38478. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38479. }
  38480. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  38481. }
  38482. else {
  38483. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  38484. }
  38485. scene.pushGeometry(geometry, true);
  38486. return geometry;
  38487. };
  38488. return Geometry;
  38489. }());
  38490. BABYLON.Geometry = Geometry;
  38491. // Primitives
  38492. /// Abstract class
  38493. /**
  38494. * Abstract class used to provide common services for all typed geometries
  38495. */
  38496. var _PrimitiveGeometry = /** @class */ (function (_super) {
  38497. __extends(_PrimitiveGeometry, _super);
  38498. /**
  38499. * Creates a new typed geometry
  38500. * @param id defines the unique ID of the geometry
  38501. * @param scene defines the hosting scene
  38502. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  38503. * @param mesh defines the hosting mesh (can be null)
  38504. */
  38505. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  38506. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  38507. if (mesh === void 0) { mesh = null; }
  38508. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  38509. _this._canBeRegenerated = _canBeRegenerated;
  38510. _this._beingRegenerated = true;
  38511. _this.regenerate();
  38512. _this._beingRegenerated = false;
  38513. return _this;
  38514. }
  38515. /**
  38516. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  38517. * @returns true if the geometry can be regenerated
  38518. */
  38519. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  38520. return this._canBeRegenerated;
  38521. };
  38522. /**
  38523. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  38524. */
  38525. _PrimitiveGeometry.prototype.regenerate = function () {
  38526. if (!this._canBeRegenerated) {
  38527. return;
  38528. }
  38529. this._beingRegenerated = true;
  38530. this.setAllVerticesData(this._regenerateVertexData(), false);
  38531. this._beingRegenerated = false;
  38532. };
  38533. /**
  38534. * Clone the geometry
  38535. * @param id defines the unique ID of the new geometry
  38536. * @returns the new geometry
  38537. */
  38538. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  38539. return _super.prototype.copy.call(this, id);
  38540. };
  38541. // overrides
  38542. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38543. if (!this._beingRegenerated) {
  38544. return;
  38545. }
  38546. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  38547. };
  38548. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  38549. if (!this._beingRegenerated) {
  38550. return;
  38551. }
  38552. _super.prototype.setVerticesData.call(this, kind, data, false);
  38553. };
  38554. // to override
  38555. /** @ignore */
  38556. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  38557. throw new Error("Abstract method");
  38558. };
  38559. _PrimitiveGeometry.prototype.copy = function (id) {
  38560. throw new Error("Must be overriden in sub-classes.");
  38561. };
  38562. _PrimitiveGeometry.prototype.serialize = function () {
  38563. var serializationObject = _super.prototype.serialize.call(this);
  38564. serializationObject.canBeRegenerated = this.canBeRegenerated();
  38565. return serializationObject;
  38566. };
  38567. return _PrimitiveGeometry;
  38568. }(Geometry));
  38569. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  38570. /**
  38571. * Creates a ribbon geometry
  38572. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  38573. */
  38574. var RibbonGeometry = /** @class */ (function (_super) {
  38575. __extends(RibbonGeometry, _super);
  38576. /**
  38577. * Creates a ribbon geometry
  38578. * @param id defines the unique ID of the geometry
  38579. * @param scene defines the hosting scene
  38580. * @param pathArray defines the array of paths to use
  38581. * @param closeArray defines if the last path and the first path must be joined
  38582. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  38583. * @param offset defines the offset between points
  38584. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  38585. * @param mesh defines the hosting mesh (can be null)
  38586. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  38587. */
  38588. function RibbonGeometry(id, scene,
  38589. /**
  38590. * Defines the array of paths to use
  38591. */
  38592. pathArray,
  38593. /**
  38594. * Defines if the last and first points of each path in your pathArray must be joined
  38595. */
  38596. closeArray,
  38597. /**
  38598. * Defines if the last and first points of each path in your pathArray must be joined
  38599. */
  38600. closePath,
  38601. /**
  38602. * Defines the offset between points
  38603. */
  38604. offset, canBeRegenerated, mesh,
  38605. /**
  38606. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  38607. */
  38608. side) {
  38609. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  38610. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38611. _this.pathArray = pathArray;
  38612. _this.closeArray = closeArray;
  38613. _this.closePath = closePath;
  38614. _this.offset = offset;
  38615. _this.side = side;
  38616. return _this;
  38617. }
  38618. /** @ignore */
  38619. RibbonGeometry.prototype._regenerateVertexData = function () {
  38620. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  38621. };
  38622. RibbonGeometry.prototype.copy = function (id) {
  38623. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  38624. };
  38625. return RibbonGeometry;
  38626. }(_PrimitiveGeometry));
  38627. BABYLON.RibbonGeometry = RibbonGeometry;
  38628. /**
  38629. * Creates a box geometry
  38630. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  38631. */
  38632. var BoxGeometry = /** @class */ (function (_super) {
  38633. __extends(BoxGeometry, _super);
  38634. /**
  38635. * Creates a box geometry
  38636. * @param id defines the unique ID of the geometry
  38637. * @param scene defines the hosting scene
  38638. * @param size defines the zise of the box (width, height and depth are the same)
  38639. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  38640. * @param mesh defines the hosting mesh (can be null)
  38641. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  38642. */
  38643. function BoxGeometry(id, scene,
  38644. /**
  38645. * Defines the zise of the box (width, height and depth are the same)
  38646. */
  38647. size, canBeRegenerated, mesh,
  38648. /**
  38649. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  38650. */
  38651. side) {
  38652. if (mesh === void 0) { mesh = null; }
  38653. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  38654. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38655. _this.size = size;
  38656. _this.side = side;
  38657. return _this;
  38658. }
  38659. BoxGeometry.prototype._regenerateVertexData = function () {
  38660. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  38661. };
  38662. BoxGeometry.prototype.copy = function (id) {
  38663. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  38664. };
  38665. BoxGeometry.prototype.serialize = function () {
  38666. var serializationObject = _super.prototype.serialize.call(this);
  38667. serializationObject.size = this.size;
  38668. return serializationObject;
  38669. };
  38670. BoxGeometry.Parse = function (parsedBox, scene) {
  38671. if (scene.getGeometryByID(parsedBox.id)) {
  38672. return null; // null since geometry could be something else than a box...
  38673. }
  38674. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  38675. if (BABYLON.Tags) {
  38676. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  38677. }
  38678. scene.pushGeometry(box, true);
  38679. return box;
  38680. };
  38681. return BoxGeometry;
  38682. }(_PrimitiveGeometry));
  38683. BABYLON.BoxGeometry = BoxGeometry;
  38684. /**
  38685. * Creates a sphere geometry
  38686. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  38687. */
  38688. var SphereGeometry = /** @class */ (function (_super) {
  38689. __extends(SphereGeometry, _super);
  38690. /**
  38691. * Create a new sphere geometry
  38692. * @param id defines the unique ID of the geometry
  38693. * @param scene defines the hosting scene
  38694. * @param segments defines the number of segments to use to create the sphere
  38695. * @param diameter defines the diameter of the sphere
  38696. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  38697. * @param mesh defines the hosting mesh (can be null)
  38698. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  38699. */
  38700. function SphereGeometry(id, scene,
  38701. /**
  38702. * Defines the number of segments to use to create the sphere
  38703. */
  38704. segments,
  38705. /**
  38706. * Defines the diameter of the sphere
  38707. */
  38708. diameter, canBeRegenerated, mesh,
  38709. /**
  38710. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  38711. */
  38712. side) {
  38713. if (mesh === void 0) { mesh = null; }
  38714. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  38715. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38716. _this.segments = segments;
  38717. _this.diameter = diameter;
  38718. _this.side = side;
  38719. return _this;
  38720. }
  38721. SphereGeometry.prototype._regenerateVertexData = function () {
  38722. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  38723. };
  38724. SphereGeometry.prototype.copy = function (id) {
  38725. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  38726. };
  38727. SphereGeometry.prototype.serialize = function () {
  38728. var serializationObject = _super.prototype.serialize.call(this);
  38729. serializationObject.segments = this.segments;
  38730. serializationObject.diameter = this.diameter;
  38731. return serializationObject;
  38732. };
  38733. SphereGeometry.Parse = function (parsedSphere, scene) {
  38734. if (scene.getGeometryByID(parsedSphere.id)) {
  38735. return null; // null since geometry could be something else than a sphere...
  38736. }
  38737. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  38738. if (BABYLON.Tags) {
  38739. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  38740. }
  38741. scene.pushGeometry(sphere, true);
  38742. return sphere;
  38743. };
  38744. return SphereGeometry;
  38745. }(_PrimitiveGeometry));
  38746. BABYLON.SphereGeometry = SphereGeometry;
  38747. /**
  38748. * Creates a disc geometry
  38749. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  38750. */
  38751. var DiscGeometry = /** @class */ (function (_super) {
  38752. __extends(DiscGeometry, _super);
  38753. /**
  38754. * Creates a new disc geometry
  38755. * @param id defines the unique ID of the geometry
  38756. * @param scene defines the hosting scene
  38757. * @param radius defines the radius of the disc
  38758. * @param tessellation defines the tesselation factor to apply to the disc
  38759. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  38760. * @param mesh defines the hosting mesh (can be null)
  38761. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  38762. */
  38763. function DiscGeometry(id, scene,
  38764. /**
  38765. * Defines the radius of the disc
  38766. */
  38767. radius,
  38768. /**
  38769. * Defines the tesselation factor to apply to the disc
  38770. */
  38771. tessellation, canBeRegenerated, mesh,
  38772. /**
  38773. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  38774. */
  38775. side) {
  38776. if (mesh === void 0) { mesh = null; }
  38777. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  38778. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38779. _this.radius = radius;
  38780. _this.tessellation = tessellation;
  38781. _this.side = side;
  38782. return _this;
  38783. }
  38784. DiscGeometry.prototype._regenerateVertexData = function () {
  38785. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  38786. };
  38787. DiscGeometry.prototype.copy = function (id) {
  38788. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  38789. };
  38790. return DiscGeometry;
  38791. }(_PrimitiveGeometry));
  38792. BABYLON.DiscGeometry = DiscGeometry;
  38793. /**
  38794. * Creates a new cylinder geometry
  38795. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  38796. */
  38797. var CylinderGeometry = /** @class */ (function (_super) {
  38798. __extends(CylinderGeometry, _super);
  38799. /**
  38800. * Creates a new cylinder geometry
  38801. * @param id defines the unique ID of the geometry
  38802. * @param scene defines the hosting scene
  38803. * @param height defines the height of the cylinder
  38804. * @param diameterTop defines the diameter of the cylinder's top cap
  38805. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  38806. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  38807. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  38808. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  38809. * @param mesh defines the hosting mesh (can be null)
  38810. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  38811. */
  38812. function CylinderGeometry(id, scene,
  38813. /**
  38814. * Defines the height of the cylinder
  38815. */
  38816. height,
  38817. /**
  38818. * Defines the diameter of the cylinder's top cap
  38819. */
  38820. diameterTop,
  38821. /**
  38822. * Defines the diameter of the cylinder's bottom cap
  38823. */
  38824. diameterBottom,
  38825. /**
  38826. * Defines the tessellation factor to apply to the cylinder
  38827. */
  38828. tessellation,
  38829. /**
  38830. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  38831. */
  38832. subdivisions, canBeRegenerated, mesh,
  38833. /**
  38834. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  38835. */
  38836. side) {
  38837. if (subdivisions === void 0) { subdivisions = 1; }
  38838. if (mesh === void 0) { mesh = null; }
  38839. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  38840. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38841. _this.height = height;
  38842. _this.diameterTop = diameterTop;
  38843. _this.diameterBottom = diameterBottom;
  38844. _this.tessellation = tessellation;
  38845. _this.subdivisions = subdivisions;
  38846. _this.side = side;
  38847. return _this;
  38848. }
  38849. CylinderGeometry.prototype._regenerateVertexData = function () {
  38850. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  38851. };
  38852. CylinderGeometry.prototype.copy = function (id) {
  38853. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  38854. };
  38855. CylinderGeometry.prototype.serialize = function () {
  38856. var serializationObject = _super.prototype.serialize.call(this);
  38857. serializationObject.height = this.height;
  38858. serializationObject.diameterTop = this.diameterTop;
  38859. serializationObject.diameterBottom = this.diameterBottom;
  38860. serializationObject.tessellation = this.tessellation;
  38861. return serializationObject;
  38862. };
  38863. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  38864. if (scene.getGeometryByID(parsedCylinder.id)) {
  38865. return null; // null since geometry could be something else than a cylinder...
  38866. }
  38867. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  38868. if (BABYLON.Tags) {
  38869. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  38870. }
  38871. scene.pushGeometry(cylinder, true);
  38872. return cylinder;
  38873. };
  38874. return CylinderGeometry;
  38875. }(_PrimitiveGeometry));
  38876. BABYLON.CylinderGeometry = CylinderGeometry;
  38877. /**
  38878. * Creates a new torus geometry
  38879. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  38880. */
  38881. var TorusGeometry = /** @class */ (function (_super) {
  38882. __extends(TorusGeometry, _super);
  38883. /**
  38884. * Creates a new torus geometry
  38885. * @param id defines the unique ID of the geometry
  38886. * @param scene defines the hosting scene
  38887. * @param diameter defines the diameter of the torus
  38888. * @param thickness defines the thickness of the torus (ie. internal diameter)
  38889. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  38890. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  38891. * @param mesh defines the hosting mesh (can be null)
  38892. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  38893. */
  38894. function TorusGeometry(id, scene,
  38895. /**
  38896. * Defines the diameter of the torus
  38897. */
  38898. diameter,
  38899. /**
  38900. * Defines the thickness of the torus (ie. internal diameter)
  38901. */
  38902. thickness,
  38903. /**
  38904. * Defines the tesselation factor to apply to the torus
  38905. */
  38906. tessellation, canBeRegenerated, mesh,
  38907. /**
  38908. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  38909. */
  38910. side) {
  38911. if (mesh === void 0) { mesh = null; }
  38912. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  38913. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38914. _this.diameter = diameter;
  38915. _this.thickness = thickness;
  38916. _this.tessellation = tessellation;
  38917. _this.side = side;
  38918. return _this;
  38919. }
  38920. TorusGeometry.prototype._regenerateVertexData = function () {
  38921. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  38922. };
  38923. TorusGeometry.prototype.copy = function (id) {
  38924. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  38925. };
  38926. TorusGeometry.prototype.serialize = function () {
  38927. var serializationObject = _super.prototype.serialize.call(this);
  38928. serializationObject.diameter = this.diameter;
  38929. serializationObject.thickness = this.thickness;
  38930. serializationObject.tessellation = this.tessellation;
  38931. return serializationObject;
  38932. };
  38933. TorusGeometry.Parse = function (parsedTorus, scene) {
  38934. if (scene.getGeometryByID(parsedTorus.id)) {
  38935. return null; // null since geometry could be something else than a torus...
  38936. }
  38937. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  38938. if (BABYLON.Tags) {
  38939. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  38940. }
  38941. scene.pushGeometry(torus, true);
  38942. return torus;
  38943. };
  38944. return TorusGeometry;
  38945. }(_PrimitiveGeometry));
  38946. BABYLON.TorusGeometry = TorusGeometry;
  38947. /**
  38948. * Creates a new ground geometry
  38949. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  38950. */
  38951. var GroundGeometry = /** @class */ (function (_super) {
  38952. __extends(GroundGeometry, _super);
  38953. /**
  38954. * Creates a new ground geometry
  38955. * @param id defines the unique ID of the geometry
  38956. * @param scene defines the hosting scene
  38957. * @param width defines the width of the ground
  38958. * @param height defines the height of the ground
  38959. * @param subdivisions defines the subdivisions to apply to the ground
  38960. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  38961. * @param mesh defines the hosting mesh (can be null)
  38962. */
  38963. function GroundGeometry(id, scene,
  38964. /**
  38965. * Defines the width of the ground
  38966. */
  38967. width,
  38968. /**
  38969. * Defines the height of the ground
  38970. */
  38971. height,
  38972. /**
  38973. * Defines the subdivisions to apply to the ground
  38974. */
  38975. subdivisions, canBeRegenerated, mesh) {
  38976. if (mesh === void 0) { mesh = null; }
  38977. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38978. _this.width = width;
  38979. _this.height = height;
  38980. _this.subdivisions = subdivisions;
  38981. return _this;
  38982. }
  38983. GroundGeometry.prototype._regenerateVertexData = function () {
  38984. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  38985. };
  38986. GroundGeometry.prototype.copy = function (id) {
  38987. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  38988. };
  38989. GroundGeometry.prototype.serialize = function () {
  38990. var serializationObject = _super.prototype.serialize.call(this);
  38991. serializationObject.width = this.width;
  38992. serializationObject.height = this.height;
  38993. serializationObject.subdivisions = this.subdivisions;
  38994. return serializationObject;
  38995. };
  38996. GroundGeometry.Parse = function (parsedGround, scene) {
  38997. if (scene.getGeometryByID(parsedGround.id)) {
  38998. return null; // null since geometry could be something else than a ground...
  38999. }
  39000. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  39001. if (BABYLON.Tags) {
  39002. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  39003. }
  39004. scene.pushGeometry(ground, true);
  39005. return ground;
  39006. };
  39007. return GroundGeometry;
  39008. }(_PrimitiveGeometry));
  39009. BABYLON.GroundGeometry = GroundGeometry;
  39010. /**
  39011. * Creates a tiled ground geometry
  39012. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  39013. */
  39014. var TiledGroundGeometry = /** @class */ (function (_super) {
  39015. __extends(TiledGroundGeometry, _super);
  39016. /**
  39017. * Creates a tiled ground geometry
  39018. * @param id defines the unique ID of the geometry
  39019. * @param scene defines the hosting scene
  39020. * @param xmin defines the minimum value on X axis
  39021. * @param zmin defines the minimum value on Z axis
  39022. * @param xmax defines the maximum value on X axis
  39023. * @param zmax defines the maximum value on Z axis
  39024. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  39025. * @param precision defines the precision to use when computing the tiles
  39026. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39027. * @param mesh defines the hosting mesh (can be null)
  39028. */
  39029. function TiledGroundGeometry(id, scene,
  39030. /**
  39031. * Defines the minimum value on X axis
  39032. */
  39033. xmin,
  39034. /**
  39035. * Defines the minimum value on Z axis
  39036. */
  39037. zmin,
  39038. /**
  39039. * Defines the maximum value on X axis
  39040. */
  39041. xmax,
  39042. /**
  39043. * Defines the maximum value on Z axis
  39044. */
  39045. zmax,
  39046. /**
  39047. * Defines the subdivisions to apply to the ground
  39048. */
  39049. subdivisions,
  39050. /**
  39051. * Defines the precision to use when computing the tiles
  39052. */
  39053. precision, canBeRegenerated, mesh) {
  39054. if (mesh === void 0) { mesh = null; }
  39055. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39056. _this.xmin = xmin;
  39057. _this.zmin = zmin;
  39058. _this.xmax = xmax;
  39059. _this.zmax = zmax;
  39060. _this.subdivisions = subdivisions;
  39061. _this.precision = precision;
  39062. return _this;
  39063. }
  39064. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  39065. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  39066. };
  39067. TiledGroundGeometry.prototype.copy = function (id) {
  39068. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  39069. };
  39070. return TiledGroundGeometry;
  39071. }(_PrimitiveGeometry));
  39072. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  39073. /**
  39074. * Creates a plane geometry
  39075. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  39076. */
  39077. var PlaneGeometry = /** @class */ (function (_super) {
  39078. __extends(PlaneGeometry, _super);
  39079. /**
  39080. * Creates a plane geometry
  39081. * @param id defines the unique ID of the geometry
  39082. * @param scene defines the hosting scene
  39083. * @param size defines the size of the plane (width === height)
  39084. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39085. * @param mesh defines the hosting mesh (can be null)
  39086. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39087. */
  39088. function PlaneGeometry(id, scene,
  39089. /**
  39090. * Defines the size of the plane (width === height)
  39091. */
  39092. size, canBeRegenerated, mesh,
  39093. /**
  39094. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39095. */
  39096. side) {
  39097. if (mesh === void 0) { mesh = null; }
  39098. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39099. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39100. _this.size = size;
  39101. _this.side = side;
  39102. return _this;
  39103. }
  39104. PlaneGeometry.prototype._regenerateVertexData = function () {
  39105. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  39106. };
  39107. PlaneGeometry.prototype.copy = function (id) {
  39108. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  39109. };
  39110. PlaneGeometry.prototype.serialize = function () {
  39111. var serializationObject = _super.prototype.serialize.call(this);
  39112. serializationObject.size = this.size;
  39113. return serializationObject;
  39114. };
  39115. PlaneGeometry.Parse = function (parsedPlane, scene) {
  39116. if (scene.getGeometryByID(parsedPlane.id)) {
  39117. return null; // null since geometry could be something else than a ground...
  39118. }
  39119. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  39120. if (BABYLON.Tags) {
  39121. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  39122. }
  39123. scene.pushGeometry(plane, true);
  39124. return plane;
  39125. };
  39126. return PlaneGeometry;
  39127. }(_PrimitiveGeometry));
  39128. BABYLON.PlaneGeometry = PlaneGeometry;
  39129. /**
  39130. * Creates a torus knot geometry
  39131. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  39132. */
  39133. var TorusKnotGeometry = /** @class */ (function (_super) {
  39134. __extends(TorusKnotGeometry, _super);
  39135. /**
  39136. * Creates a torus knot geometry
  39137. * @param id defines the unique ID of the geometry
  39138. * @param scene defines the hosting scene
  39139. * @param radius defines the radius of the torus knot
  39140. * @param tube defines the thickness of the torus knot tube
  39141. * @param radialSegments defines the number of radial segments
  39142. * @param tubularSegments defines the number of tubular segments
  39143. * @param p defines the first number of windings
  39144. * @param q defines the second number of windings
  39145. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39146. * @param mesh defines the hosting mesh (can be null)
  39147. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39148. */
  39149. function TorusKnotGeometry(id, scene,
  39150. /**
  39151. * Defines the radius of the torus knot
  39152. */
  39153. radius,
  39154. /**
  39155. * Defines the thickness of the torus knot tube
  39156. */
  39157. tube,
  39158. /**
  39159. * Defines the number of radial segments
  39160. */
  39161. radialSegments,
  39162. /**
  39163. * Defines the number of tubular segments
  39164. */
  39165. tubularSegments,
  39166. /**
  39167. * Defines the first number of windings
  39168. */
  39169. p,
  39170. /**
  39171. * Defines the second number of windings
  39172. */
  39173. q, canBeRegenerated, mesh,
  39174. /**
  39175. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39176. */
  39177. side) {
  39178. if (mesh === void 0) { mesh = null; }
  39179. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39180. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39181. _this.radius = radius;
  39182. _this.tube = tube;
  39183. _this.radialSegments = radialSegments;
  39184. _this.tubularSegments = tubularSegments;
  39185. _this.p = p;
  39186. _this.q = q;
  39187. _this.side = side;
  39188. return _this;
  39189. }
  39190. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  39191. 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 });
  39192. };
  39193. TorusKnotGeometry.prototype.copy = function (id) {
  39194. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  39195. };
  39196. TorusKnotGeometry.prototype.serialize = function () {
  39197. var serializationObject = _super.prototype.serialize.call(this);
  39198. serializationObject.radius = this.radius;
  39199. serializationObject.tube = this.tube;
  39200. serializationObject.radialSegments = this.radialSegments;
  39201. serializationObject.tubularSegments = this.tubularSegments;
  39202. serializationObject.p = this.p;
  39203. serializationObject.q = this.q;
  39204. return serializationObject;
  39205. };
  39206. ;
  39207. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  39208. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  39209. return null; // null since geometry could be something else than a ground...
  39210. }
  39211. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  39212. if (BABYLON.Tags) {
  39213. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  39214. }
  39215. scene.pushGeometry(torusKnot, true);
  39216. return torusKnot;
  39217. };
  39218. return TorusKnotGeometry;
  39219. }(_PrimitiveGeometry));
  39220. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  39221. //}
  39222. })(BABYLON || (BABYLON = {}));
  39223. //# sourceMappingURL=babylon.geometry.js.map
  39224. "use strict";
  39225. var BABYLON;
  39226. (function (BABYLON) {
  39227. /**
  39228. * PostProcessManager is used to manage one or more post processes or post process pipelines
  39229. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  39230. */
  39231. var PostProcessManager = /** @class */ (function () {
  39232. /**
  39233. * Creates a new instance PostProcess
  39234. * @param scene The scene that the post process is associated with.
  39235. */
  39236. function PostProcessManager(scene) {
  39237. this._vertexBuffers = {};
  39238. this._scene = scene;
  39239. }
  39240. PostProcessManager.prototype._prepareBuffers = function () {
  39241. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  39242. return;
  39243. }
  39244. // VBO
  39245. var vertices = [];
  39246. vertices.push(1, 1);
  39247. vertices.push(-1, 1);
  39248. vertices.push(-1, -1);
  39249. vertices.push(1, -1);
  39250. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  39251. this._buildIndexBuffer();
  39252. };
  39253. PostProcessManager.prototype._buildIndexBuffer = function () {
  39254. // Indices
  39255. var indices = [];
  39256. indices.push(0);
  39257. indices.push(1);
  39258. indices.push(2);
  39259. indices.push(0);
  39260. indices.push(2);
  39261. indices.push(3);
  39262. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  39263. };
  39264. /**
  39265. * Rebuilds the vertex buffers of the manager.
  39266. */
  39267. PostProcessManager.prototype._rebuild = function () {
  39268. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  39269. if (!vb) {
  39270. return;
  39271. }
  39272. vb._rebuild();
  39273. this._buildIndexBuffer();
  39274. };
  39275. // Methods
  39276. /**
  39277. * Prepares a frame to be run through a post process.
  39278. * @param sourceTexture The input texture to the post procesess. (default: null)
  39279. * @param postProcesses An array of post processes to be run. (default: null)
  39280. * @returns True if the post processes were able to be run.
  39281. */
  39282. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  39283. if (sourceTexture === void 0) { sourceTexture = null; }
  39284. if (postProcesses === void 0) { postProcesses = null; }
  39285. var camera = this._scene.activeCamera;
  39286. if (!camera) {
  39287. return false;
  39288. }
  39289. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  39290. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  39291. return false;
  39292. }
  39293. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  39294. return true;
  39295. };
  39296. /**
  39297. * Manually render a set of post processes to a texture.
  39298. * @param postProcesses An array of post processes to be run.
  39299. * @param targetTexture The target texture to render to.
  39300. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  39301. */
  39302. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  39303. if (targetTexture === void 0) { targetTexture = null; }
  39304. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  39305. var engine = this._scene.getEngine();
  39306. for (var index = 0; index < postProcesses.length; index++) {
  39307. if (index < postProcesses.length - 1) {
  39308. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  39309. }
  39310. else {
  39311. if (targetTexture) {
  39312. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  39313. }
  39314. else {
  39315. engine.restoreDefaultFramebuffer();
  39316. }
  39317. }
  39318. var pp = postProcesses[index];
  39319. var effect = pp.apply();
  39320. if (effect) {
  39321. pp.onBeforeRenderObservable.notifyObservers(effect);
  39322. // VBOs
  39323. this._prepareBuffers();
  39324. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  39325. // Draw order
  39326. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  39327. pp.onAfterRenderObservable.notifyObservers(effect);
  39328. }
  39329. }
  39330. // Restore depth buffer
  39331. engine.setDepthBuffer(true);
  39332. engine.setDepthWrite(true);
  39333. };
  39334. /**
  39335. * Finalize the result of the output of the postprocesses.
  39336. * @param doNotPresent If true the result will not be displayed to the screen.
  39337. * @param targetTexture The target texture to render to.
  39338. * @param faceIndex The index of the face to bind the target texture to.
  39339. * @param postProcesses The array of post processes to render.
  39340. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  39341. */
  39342. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  39343. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  39344. var camera = this._scene.activeCamera;
  39345. if (!camera) {
  39346. return;
  39347. }
  39348. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  39349. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  39350. return;
  39351. }
  39352. var engine = this._scene.getEngine();
  39353. for (var index = 0, len = postProcesses.length; index < len; index++) {
  39354. var pp = postProcesses[index];
  39355. if (index < len - 1) {
  39356. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  39357. }
  39358. else {
  39359. if (targetTexture) {
  39360. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  39361. pp._outputTexture = targetTexture;
  39362. }
  39363. else {
  39364. engine.restoreDefaultFramebuffer();
  39365. pp._outputTexture = null;
  39366. }
  39367. }
  39368. if (doNotPresent) {
  39369. break;
  39370. }
  39371. var effect = pp.apply();
  39372. if (effect) {
  39373. pp.onBeforeRenderObservable.notifyObservers(effect);
  39374. // VBOs
  39375. this._prepareBuffers();
  39376. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  39377. // Draw order
  39378. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  39379. pp.onAfterRenderObservable.notifyObservers(effect);
  39380. }
  39381. }
  39382. // Restore states
  39383. engine.setDepthBuffer(true);
  39384. engine.setDepthWrite(true);
  39385. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  39386. };
  39387. /**
  39388. * Disposes of the post process manager.
  39389. */
  39390. PostProcessManager.prototype.dispose = function () {
  39391. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  39392. if (buffer) {
  39393. buffer.dispose();
  39394. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  39395. }
  39396. if (this._indexBuffer) {
  39397. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  39398. this._indexBuffer = null;
  39399. }
  39400. };
  39401. return PostProcessManager;
  39402. }());
  39403. BABYLON.PostProcessManager = PostProcessManager;
  39404. })(BABYLON || (BABYLON = {}));
  39405. //# sourceMappingURL=babylon.postProcessManager.js.map
  39406. "use strict";
  39407. var BABYLON;
  39408. (function (BABYLON) {
  39409. /**
  39410. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  39411. */
  39412. var PerformanceMonitor = /** @class */ (function () {
  39413. /**
  39414. * constructor
  39415. * @param frameSampleSize The number of samples required to saturate the sliding window
  39416. */
  39417. function PerformanceMonitor(frameSampleSize) {
  39418. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  39419. this._enabled = true;
  39420. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  39421. }
  39422. /**
  39423. * Samples current frame
  39424. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  39425. */
  39426. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  39427. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  39428. if (!this._enabled)
  39429. return;
  39430. if (this._lastFrameTimeMs != null) {
  39431. var dt = timeMs - this._lastFrameTimeMs;
  39432. this._rollingFrameTime.add(dt);
  39433. }
  39434. this._lastFrameTimeMs = timeMs;
  39435. };
  39436. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  39437. /**
  39438. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  39439. * @return Average frame time in milliseconds
  39440. */
  39441. get: function () {
  39442. return this._rollingFrameTime.average;
  39443. },
  39444. enumerable: true,
  39445. configurable: true
  39446. });
  39447. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  39448. /**
  39449. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  39450. * @return Frame time variance in milliseconds squared
  39451. */
  39452. get: function () {
  39453. return this._rollingFrameTime.variance;
  39454. },
  39455. enumerable: true,
  39456. configurable: true
  39457. });
  39458. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  39459. /**
  39460. * Returns the frame time of the most recent frame
  39461. * @return Frame time in milliseconds
  39462. */
  39463. get: function () {
  39464. return this._rollingFrameTime.history(0);
  39465. },
  39466. enumerable: true,
  39467. configurable: true
  39468. });
  39469. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  39470. /**
  39471. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  39472. * @return Framerate in frames per second
  39473. */
  39474. get: function () {
  39475. return 1000.0 / this._rollingFrameTime.average;
  39476. },
  39477. enumerable: true,
  39478. configurable: true
  39479. });
  39480. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  39481. /**
  39482. * Returns the average framerate in frames per second using the most recent frame time
  39483. * @return Framerate in frames per second
  39484. */
  39485. get: function () {
  39486. var history = this._rollingFrameTime.history(0);
  39487. if (history === 0) {
  39488. return 0;
  39489. }
  39490. return 1000.0 / history;
  39491. },
  39492. enumerable: true,
  39493. configurable: true
  39494. });
  39495. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  39496. /**
  39497. * Returns true if enough samples have been taken to completely fill the sliding window
  39498. * @return true if saturated
  39499. */
  39500. get: function () {
  39501. return this._rollingFrameTime.isSaturated();
  39502. },
  39503. enumerable: true,
  39504. configurable: true
  39505. });
  39506. /**
  39507. * Enables contributions to the sliding window sample set
  39508. */
  39509. PerformanceMonitor.prototype.enable = function () {
  39510. this._enabled = true;
  39511. };
  39512. /**
  39513. * Disables contributions to the sliding window sample set
  39514. * Samples will not be interpolated over the disabled period
  39515. */
  39516. PerformanceMonitor.prototype.disable = function () {
  39517. this._enabled = false;
  39518. //clear last sample to avoid interpolating over the disabled period when next enabled
  39519. this._lastFrameTimeMs = null;
  39520. };
  39521. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  39522. /**
  39523. * Returns true if sampling is enabled
  39524. * @return true if enabled
  39525. */
  39526. get: function () {
  39527. return this._enabled;
  39528. },
  39529. enumerable: true,
  39530. configurable: true
  39531. });
  39532. /**
  39533. * Resets performance monitor
  39534. */
  39535. PerformanceMonitor.prototype.reset = function () {
  39536. //clear last sample to avoid interpolating over the disabled period when next enabled
  39537. this._lastFrameTimeMs = null;
  39538. //wipe record
  39539. this._rollingFrameTime.reset();
  39540. };
  39541. return PerformanceMonitor;
  39542. }());
  39543. BABYLON.PerformanceMonitor = PerformanceMonitor;
  39544. /**
  39545. * RollingAverage
  39546. *
  39547. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  39548. */
  39549. var RollingAverage = /** @class */ (function () {
  39550. /**
  39551. * constructor
  39552. * @param length The number of samples required to saturate the sliding window
  39553. */
  39554. function RollingAverage(length) {
  39555. this._samples = new Array(length);
  39556. this.reset();
  39557. }
  39558. /**
  39559. * Adds a sample to the sample set
  39560. * @param v The sample value
  39561. */
  39562. RollingAverage.prototype.add = function (v) {
  39563. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  39564. var delta;
  39565. //we need to check if we've already wrapped round
  39566. if (this.isSaturated()) {
  39567. //remove bottom of stack from mean
  39568. var bottomValue = this._samples[this._pos];
  39569. delta = bottomValue - this.average;
  39570. this.average -= delta / (this._sampleCount - 1);
  39571. this._m2 -= delta * (bottomValue - this.average);
  39572. }
  39573. else {
  39574. this._sampleCount++;
  39575. }
  39576. //add new value to mean
  39577. delta = v - this.average;
  39578. this.average += delta / (this._sampleCount);
  39579. this._m2 += delta * (v - this.average);
  39580. //set the new variance
  39581. this.variance = this._m2 / (this._sampleCount - 1);
  39582. this._samples[this._pos] = v;
  39583. this._pos++;
  39584. this._pos %= this._samples.length; //positive wrap around
  39585. };
  39586. /**
  39587. * Returns previously added values or null if outside of history or outside the sliding window domain
  39588. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  39589. * @return Value previously recorded with add() or null if outside of range
  39590. */
  39591. RollingAverage.prototype.history = function (i) {
  39592. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  39593. return 0;
  39594. }
  39595. var i0 = this._wrapPosition(this._pos - 1.0);
  39596. return this._samples[this._wrapPosition(i0 - i)];
  39597. };
  39598. /**
  39599. * Returns true if enough samples have been taken to completely fill the sliding window
  39600. * @return true if sample-set saturated
  39601. */
  39602. RollingAverage.prototype.isSaturated = function () {
  39603. return this._sampleCount >= this._samples.length;
  39604. };
  39605. /**
  39606. * Resets the rolling average (equivalent to 0 samples taken so far)
  39607. */
  39608. RollingAverage.prototype.reset = function () {
  39609. this.average = 0;
  39610. this.variance = 0;
  39611. this._sampleCount = 0;
  39612. this._pos = 0;
  39613. this._m2 = 0;
  39614. };
  39615. /**
  39616. * Wraps a value around the sample range boundaries
  39617. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  39618. * @return Wrapped position in sample range
  39619. */
  39620. RollingAverage.prototype._wrapPosition = function (i) {
  39621. var max = this._samples.length;
  39622. return ((i % max) + max) % max;
  39623. };
  39624. return RollingAverage;
  39625. }());
  39626. BABYLON.RollingAverage = RollingAverage;
  39627. })(BABYLON || (BABYLON = {}));
  39628. //# sourceMappingURL=babylon.performanceMonitor.js.map
  39629. "use strict";
  39630. var BABYLON;
  39631. (function (BABYLON) {
  39632. /**
  39633. * This groups together the common properties used for image processing either in direct forward pass
  39634. * or through post processing effect depending on the use of the image processing pipeline in your scene
  39635. * or not.
  39636. */
  39637. var ImageProcessingConfiguration = /** @class */ (function () {
  39638. function ImageProcessingConfiguration() {
  39639. /**
  39640. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  39641. */
  39642. this.colorCurves = new BABYLON.ColorCurves();
  39643. this._colorCurvesEnabled = false;
  39644. this._colorGradingEnabled = false;
  39645. this._colorGradingWithGreenDepth = true;
  39646. this._colorGradingBGR = true;
  39647. this._exposure = 1.0;
  39648. this._toneMappingEnabled = false;
  39649. this._contrast = 1.0;
  39650. /**
  39651. * Vignette stretch size.
  39652. */
  39653. this.vignetteStretch = 0;
  39654. /**
  39655. * Vignette centre X Offset.
  39656. */
  39657. this.vignetteCentreX = 0;
  39658. /**
  39659. * Vignette centre Y Offset.
  39660. */
  39661. this.vignetteCentreY = 0;
  39662. /**
  39663. * Vignette weight or intensity of the vignette effect.
  39664. */
  39665. this.vignetteWeight = 1.5;
  39666. /**
  39667. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  39668. * if vignetteEnabled is set to true.
  39669. */
  39670. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  39671. /**
  39672. * Camera field of view used by the Vignette effect.
  39673. */
  39674. this.vignetteCameraFov = 0.5;
  39675. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  39676. this._vignetteEnabled = false;
  39677. this._applyByPostProcess = false;
  39678. this._isEnabled = true;
  39679. /**
  39680. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  39681. */
  39682. this.onUpdateParameters = new BABYLON.Observable();
  39683. }
  39684. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  39685. /**
  39686. * Gets wether the color curves effect is enabled.
  39687. */
  39688. get: function () {
  39689. return this._colorCurvesEnabled;
  39690. },
  39691. /**
  39692. * Sets wether the color curves effect is enabled.
  39693. */
  39694. set: function (value) {
  39695. if (this._colorCurvesEnabled === value) {
  39696. return;
  39697. }
  39698. this._colorCurvesEnabled = value;
  39699. this._updateParameters();
  39700. },
  39701. enumerable: true,
  39702. configurable: true
  39703. });
  39704. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  39705. /**
  39706. * Gets wether the color grading effect is enabled.
  39707. */
  39708. get: function () {
  39709. return this._colorGradingEnabled;
  39710. },
  39711. /**
  39712. * Sets wether the color grading effect is enabled.
  39713. */
  39714. set: function (value) {
  39715. if (this._colorGradingEnabled === value) {
  39716. return;
  39717. }
  39718. this._colorGradingEnabled = value;
  39719. this._updateParameters();
  39720. },
  39721. enumerable: true,
  39722. configurable: true
  39723. });
  39724. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  39725. /**
  39726. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  39727. */
  39728. get: function () {
  39729. return this._colorGradingWithGreenDepth;
  39730. },
  39731. /**
  39732. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  39733. */
  39734. set: function (value) {
  39735. if (this._colorGradingWithGreenDepth === value) {
  39736. return;
  39737. }
  39738. this._colorGradingWithGreenDepth = value;
  39739. this._updateParameters();
  39740. },
  39741. enumerable: true,
  39742. configurable: true
  39743. });
  39744. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  39745. /**
  39746. * Gets wether the color grading texture contains BGR values.
  39747. */
  39748. get: function () {
  39749. return this._colorGradingBGR;
  39750. },
  39751. /**
  39752. * Sets wether the color grading texture contains BGR values.
  39753. */
  39754. set: function (value) {
  39755. if (this._colorGradingBGR === value) {
  39756. return;
  39757. }
  39758. this._colorGradingBGR = value;
  39759. this._updateParameters();
  39760. },
  39761. enumerable: true,
  39762. configurable: true
  39763. });
  39764. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  39765. /**
  39766. * Gets the Exposure used in the effect.
  39767. */
  39768. get: function () {
  39769. return this._exposure;
  39770. },
  39771. /**
  39772. * Sets the Exposure used in the effect.
  39773. */
  39774. set: function (value) {
  39775. if (this._exposure === value) {
  39776. return;
  39777. }
  39778. this._exposure = value;
  39779. this._updateParameters();
  39780. },
  39781. enumerable: true,
  39782. configurable: true
  39783. });
  39784. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  39785. /**
  39786. * Gets wether the tone mapping effect is enabled.
  39787. */
  39788. get: function () {
  39789. return this._toneMappingEnabled;
  39790. },
  39791. /**
  39792. * Sets wether the tone mapping effect is enabled.
  39793. */
  39794. set: function (value) {
  39795. if (this._toneMappingEnabled === value) {
  39796. return;
  39797. }
  39798. this._toneMappingEnabled = value;
  39799. this._updateParameters();
  39800. },
  39801. enumerable: true,
  39802. configurable: true
  39803. });
  39804. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  39805. /**
  39806. * Gets the contrast used in the effect.
  39807. */
  39808. get: function () {
  39809. return this._contrast;
  39810. },
  39811. /**
  39812. * Sets the contrast used in the effect.
  39813. */
  39814. set: function (value) {
  39815. if (this._contrast === value) {
  39816. return;
  39817. }
  39818. this._contrast = value;
  39819. this._updateParameters();
  39820. },
  39821. enumerable: true,
  39822. configurable: true
  39823. });
  39824. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  39825. /**
  39826. * Gets the vignette blend mode allowing different kind of effect.
  39827. */
  39828. get: function () {
  39829. return this._vignetteBlendMode;
  39830. },
  39831. /**
  39832. * Sets the vignette blend mode allowing different kind of effect.
  39833. */
  39834. set: function (value) {
  39835. if (this._vignetteBlendMode === value) {
  39836. return;
  39837. }
  39838. this._vignetteBlendMode = value;
  39839. this._updateParameters();
  39840. },
  39841. enumerable: true,
  39842. configurable: true
  39843. });
  39844. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  39845. /**
  39846. * Gets wether the vignette effect is enabled.
  39847. */
  39848. get: function () {
  39849. return this._vignetteEnabled;
  39850. },
  39851. /**
  39852. * Sets wether the vignette effect is enabled.
  39853. */
  39854. set: function (value) {
  39855. if (this._vignetteEnabled === value) {
  39856. return;
  39857. }
  39858. this._vignetteEnabled = value;
  39859. this._updateParameters();
  39860. },
  39861. enumerable: true,
  39862. configurable: true
  39863. });
  39864. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  39865. /**
  39866. * Gets wether the image processing is applied through a post process or not.
  39867. */
  39868. get: function () {
  39869. return this._applyByPostProcess;
  39870. },
  39871. /**
  39872. * Sets wether the image processing is applied through a post process or not.
  39873. */
  39874. set: function (value) {
  39875. if (this._applyByPostProcess === value) {
  39876. return;
  39877. }
  39878. this._applyByPostProcess = value;
  39879. this._updateParameters();
  39880. },
  39881. enumerable: true,
  39882. configurable: true
  39883. });
  39884. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  39885. /**
  39886. * Gets wether the image processing is enabled or not.
  39887. */
  39888. get: function () {
  39889. return this._isEnabled;
  39890. },
  39891. /**
  39892. * Sets wether the image processing is enabled or not.
  39893. */
  39894. set: function (value) {
  39895. if (this._isEnabled === value) {
  39896. return;
  39897. }
  39898. this._isEnabled = value;
  39899. this._updateParameters();
  39900. },
  39901. enumerable: true,
  39902. configurable: true
  39903. });
  39904. /**
  39905. * Method called each time the image processing information changes requires to recompile the effect.
  39906. */
  39907. ImageProcessingConfiguration.prototype._updateParameters = function () {
  39908. this.onUpdateParameters.notifyObservers(this);
  39909. };
  39910. ImageProcessingConfiguration.prototype.getClassName = function () {
  39911. return "ImageProcessingConfiguration";
  39912. };
  39913. /**
  39914. * Prepare the list of uniforms associated with the Image Processing effects.
  39915. * @param uniformsList The list of uniforms used in the effect
  39916. * @param defines the list of defines currently in use
  39917. */
  39918. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  39919. if (defines.EXPOSURE) {
  39920. uniforms.push("exposureLinear");
  39921. }
  39922. if (defines.CONTRAST) {
  39923. uniforms.push("contrast");
  39924. }
  39925. if (defines.COLORGRADING) {
  39926. uniforms.push("colorTransformSettings");
  39927. }
  39928. if (defines.VIGNETTE) {
  39929. uniforms.push("vInverseScreenSize");
  39930. uniforms.push("vignetteSettings1");
  39931. uniforms.push("vignetteSettings2");
  39932. }
  39933. if (defines.COLORCURVES) {
  39934. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  39935. }
  39936. };
  39937. /**
  39938. * Prepare the list of samplers associated with the Image Processing effects.
  39939. * @param uniformsList The list of uniforms used in the effect
  39940. * @param defines the list of defines currently in use
  39941. */
  39942. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  39943. if (defines.COLORGRADING) {
  39944. samplersList.push("txColorTransform");
  39945. }
  39946. };
  39947. /**
  39948. * Prepare the list of defines associated to the shader.
  39949. * @param defines the list of defines to complete
  39950. */
  39951. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  39952. if (forPostProcess === void 0) { forPostProcess = false; }
  39953. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  39954. defines.VIGNETTE = false;
  39955. defines.TONEMAPPING = false;
  39956. defines.CONTRAST = false;
  39957. defines.EXPOSURE = false;
  39958. defines.COLORCURVES = false;
  39959. defines.COLORGRADING = false;
  39960. defines.COLORGRADING3D = false;
  39961. defines.IMAGEPROCESSING = false;
  39962. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  39963. return;
  39964. }
  39965. defines.VIGNETTE = this.vignetteEnabled;
  39966. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  39967. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  39968. defines.TONEMAPPING = this.toneMappingEnabled;
  39969. defines.CONTRAST = (this.contrast !== 1.0);
  39970. defines.EXPOSURE = (this.exposure !== 1.0);
  39971. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  39972. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  39973. if (defines.COLORGRADING) {
  39974. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  39975. }
  39976. else {
  39977. defines.COLORGRADING3D = false;
  39978. }
  39979. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  39980. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  39981. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  39982. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  39983. };
  39984. /**
  39985. * Returns true if all the image processing information are ready.
  39986. */
  39987. ImageProcessingConfiguration.prototype.isReady = function () {
  39988. // Color Grading texure can not be none blocking.
  39989. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  39990. };
  39991. /**
  39992. * Binds the image processing to the shader.
  39993. * @param effect The effect to bind to
  39994. */
  39995. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  39996. if (aspectRatio === void 0) { aspectRatio = 1; }
  39997. // Color Curves
  39998. if (this._colorCurvesEnabled && this.colorCurves) {
  39999. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  40000. }
  40001. // Vignette
  40002. if (this._vignetteEnabled) {
  40003. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  40004. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  40005. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  40006. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  40007. var vignetteScaleX = vignetteScaleY * aspectRatio;
  40008. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  40009. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  40010. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  40011. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  40012. var vignettePower = -2.0 * this.vignetteWeight;
  40013. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  40014. }
  40015. // Exposure
  40016. effect.setFloat("exposureLinear", this.exposure);
  40017. // Contrast
  40018. effect.setFloat("contrast", this.contrast);
  40019. // Color transform settings
  40020. if (this.colorGradingTexture) {
  40021. effect.setTexture("txColorTransform", this.colorGradingTexture);
  40022. var textureSize = this.colorGradingTexture.getSize().height;
  40023. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  40024. 0.5 / textureSize, // textureOffset
  40025. textureSize, // textureSize
  40026. this.colorGradingTexture.level // weight
  40027. );
  40028. }
  40029. };
  40030. /**
  40031. * Clones the current image processing instance.
  40032. * @return The cloned image processing
  40033. */
  40034. ImageProcessingConfiguration.prototype.clone = function () {
  40035. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  40036. };
  40037. /**
  40038. * Serializes the current image processing instance to a json representation.
  40039. * @return a JSON representation
  40040. */
  40041. ImageProcessingConfiguration.prototype.serialize = function () {
  40042. return BABYLON.SerializationHelper.Serialize(this);
  40043. };
  40044. /**
  40045. * Parses the image processing from a json representation.
  40046. * @param source the JSON source to parse
  40047. * @return The parsed image processing
  40048. */
  40049. ImageProcessingConfiguration.Parse = function (source) {
  40050. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  40051. };
  40052. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  40053. /**
  40054. * Used to apply the vignette as a mix with the pixel color.
  40055. */
  40056. get: function () {
  40057. return this._VIGNETTEMODE_MULTIPLY;
  40058. },
  40059. enumerable: true,
  40060. configurable: true
  40061. });
  40062. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  40063. /**
  40064. * Used to apply the vignette as a replacement of the pixel color.
  40065. */
  40066. get: function () {
  40067. return this._VIGNETTEMODE_OPAQUE;
  40068. },
  40069. enumerable: true,
  40070. configurable: true
  40071. });
  40072. // Static constants associated to the image processing.
  40073. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  40074. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  40075. __decorate([
  40076. BABYLON.serializeAsColorCurves()
  40077. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  40078. __decorate([
  40079. BABYLON.serialize()
  40080. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  40081. __decorate([
  40082. BABYLON.serializeAsTexture()
  40083. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  40084. __decorate([
  40085. BABYLON.serialize()
  40086. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  40087. __decorate([
  40088. BABYLON.serialize()
  40089. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  40090. __decorate([
  40091. BABYLON.serialize()
  40092. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  40093. __decorate([
  40094. BABYLON.serialize()
  40095. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  40096. __decorate([
  40097. BABYLON.serialize()
  40098. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  40099. __decorate([
  40100. BABYLON.serialize()
  40101. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  40102. __decorate([
  40103. BABYLON.serialize()
  40104. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  40105. __decorate([
  40106. BABYLON.serialize()
  40107. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  40108. __decorate([
  40109. BABYLON.serialize()
  40110. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  40111. __decorate([
  40112. BABYLON.serialize()
  40113. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  40114. __decorate([
  40115. BABYLON.serializeAsColor4()
  40116. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  40117. __decorate([
  40118. BABYLON.serialize()
  40119. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  40120. __decorate([
  40121. BABYLON.serialize()
  40122. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  40123. __decorate([
  40124. BABYLON.serialize()
  40125. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  40126. __decorate([
  40127. BABYLON.serialize()
  40128. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  40129. __decorate([
  40130. BABYLON.serialize()
  40131. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  40132. return ImageProcessingConfiguration;
  40133. }());
  40134. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  40135. })(BABYLON || (BABYLON = {}));
  40136. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  40137. "use strict";
  40138. var BABYLON;
  40139. (function (BABYLON) {
  40140. /**
  40141. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  40142. * It can help converting any input color in a desired output one. This can then be used to create effects
  40143. * from sepia, black and white to sixties or futuristic rendering...
  40144. *
  40145. * The only supported format is currently 3dl.
  40146. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  40147. */
  40148. var ColorGradingTexture = /** @class */ (function (_super) {
  40149. __extends(ColorGradingTexture, _super);
  40150. /**
  40151. * Instantiates a ColorGradingTexture from the following parameters.
  40152. *
  40153. * @param url The location of the color gradind data (currently only supporting 3dl)
  40154. * @param scene The scene the texture will be used in
  40155. */
  40156. function ColorGradingTexture(url, scene) {
  40157. var _this = _super.call(this, scene) || this;
  40158. if (!url) {
  40159. return _this;
  40160. }
  40161. _this._engine = scene.getEngine();
  40162. _this._textureMatrix = BABYLON.Matrix.Identity();
  40163. _this.name = url;
  40164. _this.url = url;
  40165. _this.hasAlpha = false;
  40166. _this.isCube = false;
  40167. _this.is3D = _this._engine.webGLVersion > 1;
  40168. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40169. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40170. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40171. _this.anisotropicFilteringLevel = 1;
  40172. _this._texture = _this._getFromCache(url, true);
  40173. if (!_this._texture) {
  40174. if (!scene.useDelayedTextureLoading) {
  40175. _this.loadTexture();
  40176. }
  40177. else {
  40178. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40179. }
  40180. }
  40181. return _this;
  40182. }
  40183. /**
  40184. * Returns the texture matrix used in most of the material.
  40185. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  40186. */
  40187. ColorGradingTexture.prototype.getTextureMatrix = function () {
  40188. return this._textureMatrix;
  40189. };
  40190. /**
  40191. * Occurs when the file being loaded is a .3dl LUT file.
  40192. */
  40193. ColorGradingTexture.prototype.load3dlTexture = function () {
  40194. var engine = this._engine;
  40195. var texture;
  40196. if (engine.webGLVersion === 1) {
  40197. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  40198. }
  40199. else {
  40200. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  40201. }
  40202. this._texture = texture;
  40203. var callback = function (text) {
  40204. if (typeof text !== "string") {
  40205. return;
  40206. }
  40207. var data = null;
  40208. var tempData = null;
  40209. var line;
  40210. var lines = text.split('\n');
  40211. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  40212. var maxColor = 0;
  40213. for (var i = 0; i < lines.length; i++) {
  40214. line = lines[i];
  40215. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  40216. continue;
  40217. if (line.indexOf('#') === 0)
  40218. continue;
  40219. var words = line.split(" ");
  40220. if (size === 0) {
  40221. // Number of space + one
  40222. size = words.length;
  40223. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  40224. tempData = new Float32Array(size * size * size * 4);
  40225. continue;
  40226. }
  40227. if (size != 0) {
  40228. var r = Math.max(parseInt(words[0]), 0);
  40229. var g = Math.max(parseInt(words[1]), 0);
  40230. var b = Math.max(parseInt(words[2]), 0);
  40231. maxColor = Math.max(r, maxColor);
  40232. maxColor = Math.max(g, maxColor);
  40233. maxColor = Math.max(b, maxColor);
  40234. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  40235. if (tempData) {
  40236. tempData[pixelStorageIndex + 0] = r;
  40237. tempData[pixelStorageIndex + 1] = g;
  40238. tempData[pixelStorageIndex + 2] = b;
  40239. }
  40240. pixelIndexSlice++;
  40241. if (pixelIndexSlice % size == 0) {
  40242. pixelIndexH++;
  40243. pixelIndexSlice = 0;
  40244. if (pixelIndexH % size == 0) {
  40245. pixelIndexW++;
  40246. pixelIndexH = 0;
  40247. }
  40248. }
  40249. }
  40250. }
  40251. if (tempData && data) {
  40252. for (var i = 0; i < tempData.length; i++) {
  40253. if (i > 0 && (i + 1) % 4 === 0) {
  40254. data[i] = 255;
  40255. }
  40256. else {
  40257. var value = tempData[i];
  40258. data[i] = (value / maxColor * 255);
  40259. }
  40260. }
  40261. }
  40262. if (texture.is3D) {
  40263. texture.updateSize(size, size, size);
  40264. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  40265. }
  40266. else {
  40267. texture.updateSize(size * size, size);
  40268. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  40269. }
  40270. };
  40271. var scene = this.getScene();
  40272. if (scene) {
  40273. scene._loadFile(this.url, callback);
  40274. }
  40275. else {
  40276. this._engine._loadFile(this.url, callback);
  40277. }
  40278. return this._texture;
  40279. };
  40280. /**
  40281. * Starts the loading process of the texture.
  40282. */
  40283. ColorGradingTexture.prototype.loadTexture = function () {
  40284. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  40285. this.load3dlTexture();
  40286. }
  40287. };
  40288. /**
  40289. * Clones the color gradind texture.
  40290. */
  40291. ColorGradingTexture.prototype.clone = function () {
  40292. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  40293. // Base texture
  40294. newTexture.level = this.level;
  40295. return newTexture;
  40296. };
  40297. /**
  40298. * Called during delayed load for textures.
  40299. */
  40300. ColorGradingTexture.prototype.delayLoad = function () {
  40301. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  40302. return;
  40303. }
  40304. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  40305. this._texture = this._getFromCache(this.url, true);
  40306. if (!this._texture) {
  40307. this.loadTexture();
  40308. }
  40309. };
  40310. /**
  40311. * Parses a color grading texture serialized by Babylon.
  40312. * @param parsedTexture The texture information being parsedTexture
  40313. * @param scene The scene to load the texture in
  40314. * @param rootUrl The root url of the data assets to load
  40315. * @return A color gradind texture
  40316. */
  40317. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  40318. var texture = null;
  40319. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  40320. texture = new ColorGradingTexture(parsedTexture.name, scene);
  40321. texture.name = parsedTexture.name;
  40322. texture.level = parsedTexture.level;
  40323. }
  40324. return texture;
  40325. };
  40326. /**
  40327. * Serializes the LUT texture to json format.
  40328. */
  40329. ColorGradingTexture.prototype.serialize = function () {
  40330. if (!this.name) {
  40331. return null;
  40332. }
  40333. var serializationObject = {};
  40334. serializationObject.name = this.name;
  40335. serializationObject.level = this.level;
  40336. serializationObject.customType = "BABYLON.ColorGradingTexture";
  40337. return serializationObject;
  40338. };
  40339. /**
  40340. * Empty line regex stored for GC.
  40341. */
  40342. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  40343. return ColorGradingTexture;
  40344. }(BABYLON.BaseTexture));
  40345. BABYLON.ColorGradingTexture = ColorGradingTexture;
  40346. })(BABYLON || (BABYLON = {}));
  40347. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  40348. "use strict";
  40349. var BABYLON;
  40350. (function (BABYLON) {
  40351. /**
  40352. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  40353. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  40354. * 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;
  40355. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  40356. */
  40357. var ColorCurves = /** @class */ (function () {
  40358. function ColorCurves() {
  40359. this._dirty = true;
  40360. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  40361. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  40362. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  40363. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  40364. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  40365. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  40366. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  40367. this._globalHue = 30;
  40368. this._globalDensity = 0;
  40369. this._globalSaturation = 0;
  40370. this._globalExposure = 0;
  40371. this._highlightsHue = 30;
  40372. this._highlightsDensity = 0;
  40373. this._highlightsSaturation = 0;
  40374. this._highlightsExposure = 0;
  40375. this._midtonesHue = 30;
  40376. this._midtonesDensity = 0;
  40377. this._midtonesSaturation = 0;
  40378. this._midtonesExposure = 0;
  40379. this._shadowsHue = 30;
  40380. this._shadowsDensity = 0;
  40381. this._shadowsSaturation = 0;
  40382. this._shadowsExposure = 0;
  40383. }
  40384. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  40385. /**
  40386. * Gets the global Hue value.
  40387. * 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).
  40388. */
  40389. get: function () {
  40390. return this._globalHue;
  40391. },
  40392. /**
  40393. * Sets the global Hue value.
  40394. * 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).
  40395. */
  40396. set: function (value) {
  40397. this._globalHue = value;
  40398. this._dirty = true;
  40399. },
  40400. enumerable: true,
  40401. configurable: true
  40402. });
  40403. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  40404. /**
  40405. * Gets the global Density value.
  40406. * 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.
  40407. * Values less than zero provide a filter of opposite hue.
  40408. */
  40409. get: function () {
  40410. return this._globalDensity;
  40411. },
  40412. /**
  40413. * Sets the global Density value.
  40414. * 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.
  40415. * Values less than zero provide a filter of opposite hue.
  40416. */
  40417. set: function (value) {
  40418. this._globalDensity = value;
  40419. this._dirty = true;
  40420. },
  40421. enumerable: true,
  40422. configurable: true
  40423. });
  40424. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  40425. /**
  40426. * Gets the global Saturation value.
  40427. * 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.
  40428. */
  40429. get: function () {
  40430. return this._globalSaturation;
  40431. },
  40432. /**
  40433. * Sets the global Saturation value.
  40434. * 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.
  40435. */
  40436. set: function (value) {
  40437. this._globalSaturation = value;
  40438. this._dirty = true;
  40439. },
  40440. enumerable: true,
  40441. configurable: true
  40442. });
  40443. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  40444. /**
  40445. * Gets the highlights Hue value.
  40446. * 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).
  40447. */
  40448. get: function () {
  40449. return this._highlightsHue;
  40450. },
  40451. /**
  40452. * Sets the highlights Hue value.
  40453. * 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).
  40454. */
  40455. set: function (value) {
  40456. this._highlightsHue = value;
  40457. this._dirty = true;
  40458. },
  40459. enumerable: true,
  40460. configurable: true
  40461. });
  40462. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  40463. /**
  40464. * Gets the highlights Density value.
  40465. * 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.
  40466. * Values less than zero provide a filter of opposite hue.
  40467. */
  40468. get: function () {
  40469. return this._highlightsDensity;
  40470. },
  40471. /**
  40472. * Sets the highlights Density value.
  40473. * 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.
  40474. * Values less than zero provide a filter of opposite hue.
  40475. */
  40476. set: function (value) {
  40477. this._highlightsDensity = value;
  40478. this._dirty = true;
  40479. },
  40480. enumerable: true,
  40481. configurable: true
  40482. });
  40483. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  40484. /**
  40485. * Gets the highlights Saturation value.
  40486. * 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.
  40487. */
  40488. get: function () {
  40489. return this._highlightsSaturation;
  40490. },
  40491. /**
  40492. * Sets the highlights Saturation value.
  40493. * 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.
  40494. */
  40495. set: function (value) {
  40496. this._highlightsSaturation = value;
  40497. this._dirty = true;
  40498. },
  40499. enumerable: true,
  40500. configurable: true
  40501. });
  40502. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  40503. /**
  40504. * Gets the highlights Exposure value.
  40505. * 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.
  40506. */
  40507. get: function () {
  40508. return this._highlightsExposure;
  40509. },
  40510. /**
  40511. * Sets the highlights Exposure value.
  40512. * 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.
  40513. */
  40514. set: function (value) {
  40515. this._highlightsExposure = value;
  40516. this._dirty = true;
  40517. },
  40518. enumerable: true,
  40519. configurable: true
  40520. });
  40521. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  40522. /**
  40523. * Gets the midtones Hue value.
  40524. * 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).
  40525. */
  40526. get: function () {
  40527. return this._midtonesHue;
  40528. },
  40529. /**
  40530. * Sets the midtones Hue value.
  40531. * 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).
  40532. */
  40533. set: function (value) {
  40534. this._midtonesHue = value;
  40535. this._dirty = true;
  40536. },
  40537. enumerable: true,
  40538. configurable: true
  40539. });
  40540. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  40541. /**
  40542. * Gets the midtones Density value.
  40543. * 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.
  40544. * Values less than zero provide a filter of opposite hue.
  40545. */
  40546. get: function () {
  40547. return this._midtonesDensity;
  40548. },
  40549. /**
  40550. * Sets the midtones Density value.
  40551. * 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.
  40552. * Values less than zero provide a filter of opposite hue.
  40553. */
  40554. set: function (value) {
  40555. this._midtonesDensity = value;
  40556. this._dirty = true;
  40557. },
  40558. enumerable: true,
  40559. configurable: true
  40560. });
  40561. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  40562. /**
  40563. * Gets the midtones Saturation value.
  40564. * 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.
  40565. */
  40566. get: function () {
  40567. return this._midtonesSaturation;
  40568. },
  40569. /**
  40570. * Sets the midtones Saturation value.
  40571. * 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.
  40572. */
  40573. set: function (value) {
  40574. this._midtonesSaturation = value;
  40575. this._dirty = true;
  40576. },
  40577. enumerable: true,
  40578. configurable: true
  40579. });
  40580. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  40581. /**
  40582. * Gets the midtones Exposure value.
  40583. * 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.
  40584. */
  40585. get: function () {
  40586. return this._midtonesExposure;
  40587. },
  40588. /**
  40589. * Sets the midtones Exposure value.
  40590. * 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.
  40591. */
  40592. set: function (value) {
  40593. this._midtonesExposure = value;
  40594. this._dirty = true;
  40595. },
  40596. enumerable: true,
  40597. configurable: true
  40598. });
  40599. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  40600. /**
  40601. * Gets the shadows Hue value.
  40602. * 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).
  40603. */
  40604. get: function () {
  40605. return this._shadowsHue;
  40606. },
  40607. /**
  40608. * Sets the shadows Hue value.
  40609. * 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).
  40610. */
  40611. set: function (value) {
  40612. this._shadowsHue = value;
  40613. this._dirty = true;
  40614. },
  40615. enumerable: true,
  40616. configurable: true
  40617. });
  40618. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  40619. /**
  40620. * Gets the shadows Density value.
  40621. * 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.
  40622. * Values less than zero provide a filter of opposite hue.
  40623. */
  40624. get: function () {
  40625. return this._shadowsDensity;
  40626. },
  40627. /**
  40628. * Sets the shadows Density value.
  40629. * 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.
  40630. * Values less than zero provide a filter of opposite hue.
  40631. */
  40632. set: function (value) {
  40633. this._shadowsDensity = value;
  40634. this._dirty = true;
  40635. },
  40636. enumerable: true,
  40637. configurable: true
  40638. });
  40639. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  40640. /**
  40641. * Gets the shadows Saturation value.
  40642. * 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.
  40643. */
  40644. get: function () {
  40645. return this._shadowsSaturation;
  40646. },
  40647. /**
  40648. * Sets the shadows Saturation value.
  40649. * 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.
  40650. */
  40651. set: function (value) {
  40652. this._shadowsSaturation = value;
  40653. this._dirty = true;
  40654. },
  40655. enumerable: true,
  40656. configurable: true
  40657. });
  40658. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  40659. /**
  40660. * Gets the shadows Exposure value.
  40661. * 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.
  40662. */
  40663. get: function () {
  40664. return this._shadowsExposure;
  40665. },
  40666. /**
  40667. * Sets the shadows Exposure value.
  40668. * 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.
  40669. */
  40670. set: function (value) {
  40671. this._shadowsExposure = value;
  40672. this._dirty = true;
  40673. },
  40674. enumerable: true,
  40675. configurable: true
  40676. });
  40677. ColorCurves.prototype.getClassName = function () {
  40678. return "ColorCurves";
  40679. };
  40680. /**
  40681. * Binds the color curves to the shader.
  40682. * @param colorCurves The color curve to bind
  40683. * @param effect The effect to bind to
  40684. */
  40685. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  40686. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  40687. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  40688. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  40689. if (colorCurves._dirty) {
  40690. colorCurves._dirty = false;
  40691. // Fill in global info.
  40692. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  40693. // Compute highlights info.
  40694. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  40695. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  40696. // Compute midtones info.
  40697. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  40698. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  40699. // Compute shadows info.
  40700. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  40701. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  40702. // Compute deltas (neutral is midtones).
  40703. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  40704. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  40705. }
  40706. if (effect) {
  40707. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  40708. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  40709. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  40710. }
  40711. };
  40712. /**
  40713. * Prepare the list of uniforms associated with the ColorCurves effects.
  40714. * @param uniformsList The list of uniforms used in the effect
  40715. */
  40716. ColorCurves.PrepareUniforms = function (uniformsList) {
  40717. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  40718. };
  40719. /**
  40720. * Returns color grading data based on a hue, density, saturation and exposure value.
  40721. * @param filterHue The hue of the color filter.
  40722. * @param filterDensity The density of the color filter.
  40723. * @param saturation The saturation.
  40724. * @param exposure The exposure.
  40725. * @param result The result data container.
  40726. */
  40727. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  40728. if (hue == null) {
  40729. return;
  40730. }
  40731. hue = ColorCurves.clamp(hue, 0, 360);
  40732. density = ColorCurves.clamp(density, -100, 100);
  40733. saturation = ColorCurves.clamp(saturation, -100, 100);
  40734. exposure = ColorCurves.clamp(exposure, -100, 100);
  40735. // Remap the slider/config filter density with non-linear mapping and also scale by half
  40736. // so that the maximum filter density is only 50% control. This provides fine control
  40737. // for small values and reasonable range.
  40738. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  40739. density *= 0.5;
  40740. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  40741. if (density < 0) {
  40742. density *= -1;
  40743. hue = (hue + 180) % 360;
  40744. }
  40745. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  40746. result.scaleToRef(2, result);
  40747. result.a = 1 + 0.01 * saturation;
  40748. };
  40749. /**
  40750. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  40751. * @param value The input slider value in range [-100,100].
  40752. * @returns Adjusted value.
  40753. */
  40754. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  40755. value /= 100;
  40756. var x = Math.abs(value);
  40757. x = Math.pow(x, 2);
  40758. if (value < 0) {
  40759. x *= -1;
  40760. }
  40761. x *= 100;
  40762. return x;
  40763. };
  40764. /**
  40765. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  40766. * @param hue The hue (H) input.
  40767. * @param saturation The saturation (S) input.
  40768. * @param brightness The brightness (B) input.
  40769. * @result An RGBA color represented as Vector4.
  40770. */
  40771. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  40772. var h = ColorCurves.clamp(hue, 0, 360);
  40773. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  40774. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  40775. if (s === 0) {
  40776. result.r = v;
  40777. result.g = v;
  40778. result.b = v;
  40779. }
  40780. else {
  40781. // sector 0 to 5
  40782. h /= 60;
  40783. var i = Math.floor(h);
  40784. // fractional part of h
  40785. var f = h - i;
  40786. var p = v * (1 - s);
  40787. var q = v * (1 - s * f);
  40788. var t = v * (1 - s * (1 - f));
  40789. switch (i) {
  40790. case 0:
  40791. result.r = v;
  40792. result.g = t;
  40793. result.b = p;
  40794. break;
  40795. case 1:
  40796. result.r = q;
  40797. result.g = v;
  40798. result.b = p;
  40799. break;
  40800. case 2:
  40801. result.r = p;
  40802. result.g = v;
  40803. result.b = t;
  40804. break;
  40805. case 3:
  40806. result.r = p;
  40807. result.g = q;
  40808. result.b = v;
  40809. break;
  40810. case 4:
  40811. result.r = t;
  40812. result.g = p;
  40813. result.b = v;
  40814. break;
  40815. default:// case 5:
  40816. result.r = v;
  40817. result.g = p;
  40818. result.b = q;
  40819. break;
  40820. }
  40821. }
  40822. result.a = 1;
  40823. };
  40824. /**
  40825. * Returns a value clamped between min and max
  40826. * @param value The value to clamp
  40827. * @param min The minimum of value
  40828. * @param max The maximum of value
  40829. * @returns The clamped value.
  40830. */
  40831. ColorCurves.clamp = function (value, min, max) {
  40832. return Math.min(Math.max(value, min), max);
  40833. };
  40834. /**
  40835. * Clones the current color curve instance.
  40836. * @return The cloned curves
  40837. */
  40838. ColorCurves.prototype.clone = function () {
  40839. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  40840. };
  40841. /**
  40842. * Serializes the current color curve instance to a json representation.
  40843. * @return a JSON representation
  40844. */
  40845. ColorCurves.prototype.serialize = function () {
  40846. return BABYLON.SerializationHelper.Serialize(this);
  40847. };
  40848. /**
  40849. * Parses the color curve from a json representation.
  40850. * @param source the JSON source to parse
  40851. * @return The parsed curves
  40852. */
  40853. ColorCurves.Parse = function (source) {
  40854. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  40855. };
  40856. __decorate([
  40857. BABYLON.serialize()
  40858. ], ColorCurves.prototype, "_globalHue", void 0);
  40859. __decorate([
  40860. BABYLON.serialize()
  40861. ], ColorCurves.prototype, "_globalDensity", void 0);
  40862. __decorate([
  40863. BABYLON.serialize()
  40864. ], ColorCurves.prototype, "_globalSaturation", void 0);
  40865. __decorate([
  40866. BABYLON.serialize()
  40867. ], ColorCurves.prototype, "_globalExposure", void 0);
  40868. __decorate([
  40869. BABYLON.serialize()
  40870. ], ColorCurves.prototype, "_highlightsHue", void 0);
  40871. __decorate([
  40872. BABYLON.serialize()
  40873. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  40874. __decorate([
  40875. BABYLON.serialize()
  40876. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  40877. __decorate([
  40878. BABYLON.serialize()
  40879. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  40880. __decorate([
  40881. BABYLON.serialize()
  40882. ], ColorCurves.prototype, "_midtonesHue", void 0);
  40883. __decorate([
  40884. BABYLON.serialize()
  40885. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  40886. __decorate([
  40887. BABYLON.serialize()
  40888. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  40889. __decorate([
  40890. BABYLON.serialize()
  40891. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  40892. return ColorCurves;
  40893. }());
  40894. BABYLON.ColorCurves = ColorCurves;
  40895. })(BABYLON || (BABYLON = {}));
  40896. //# sourceMappingURL=babylon.colorCurves.js.map
  40897. "use strict";
  40898. //# sourceMappingURL=babylon.behavior.js.map
  40899. "use strict";
  40900. var BABYLON;
  40901. (function (BABYLON) {
  40902. /**
  40903. * "Static Class" containing the most commonly used helper while dealing with material for
  40904. * rendering purpose.
  40905. *
  40906. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  40907. *
  40908. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  40909. */
  40910. var MaterialHelper = /** @class */ (function () {
  40911. function MaterialHelper() {
  40912. }
  40913. /**
  40914. * Bind the current view position to an effect.
  40915. * @param effect The effect to be bound
  40916. * @param scene The scene the eyes position is used from
  40917. */
  40918. MaterialHelper.BindEyePosition = function (effect, scene) {
  40919. if (scene._forcedViewPosition) {
  40920. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  40921. return;
  40922. }
  40923. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  40924. };
  40925. /**
  40926. * Helps preparing the defines values about the UVs in used in the effect.
  40927. * UVs are shared as much as we can accross chanels in the shaders.
  40928. * @param texture The texture we are preparing the UVs for
  40929. * @param defines The defines to update
  40930. * @param key The chanel key "diffuse", "specular"... used in the shader
  40931. */
  40932. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  40933. defines._needUVs = true;
  40934. defines[key] = true;
  40935. if (texture.getTextureMatrix().isIdentity(true)) {
  40936. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  40937. if (texture.coordinatesIndex === 0) {
  40938. defines["MAINUV1"] = true;
  40939. }
  40940. else {
  40941. defines["MAINUV2"] = true;
  40942. }
  40943. }
  40944. else {
  40945. defines[key + "DIRECTUV"] = 0;
  40946. }
  40947. };
  40948. /**
  40949. * Binds a texture matrix value to its corrsponding uniform
  40950. * @param texture The texture to bind the matrix for
  40951. * @param uniformBuffer The uniform buffer receivin the data
  40952. * @param key The chanel key "diffuse", "specular"... used in the shader
  40953. */
  40954. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  40955. var matrix = texture.getTextureMatrix();
  40956. if (!matrix.isIdentity(true)) {
  40957. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  40958. }
  40959. };
  40960. /**
  40961. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  40962. * @param mesh defines the current mesh
  40963. * @param scene defines the current scene
  40964. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  40965. * @param pointsCloud defines if point cloud rendering has to be turned on
  40966. * @param fogEnabled defines if fog has to be turned on
  40967. * @param alphaTest defines if alpha testing has to be turned on
  40968. * @param defines defines the current list of defines
  40969. */
  40970. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  40971. if (defines._areMiscDirty) {
  40972. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  40973. defines["POINTSIZE"] = pointsCloud;
  40974. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  40975. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  40976. defines["ALPHATEST"] = alphaTest;
  40977. }
  40978. };
  40979. /**
  40980. * Helper used to prepare the list of defines associated with frame values for shader compilation
  40981. * @param scene defines the current scene
  40982. * @param engine defines the current engine
  40983. * @param defines specifies the list of active defines
  40984. * @param useInstances defines if instances have to be turned on
  40985. * @param useClipPlane defines if clip plane have to be turned on
  40986. */
  40987. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  40988. if (useClipPlane === void 0) { useClipPlane = null; }
  40989. var changed = false;
  40990. if (useClipPlane == null) {
  40991. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  40992. }
  40993. if (defines["CLIPPLANE"] !== useClipPlane) {
  40994. defines["CLIPPLANE"] = useClipPlane;
  40995. changed = true;
  40996. }
  40997. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  40998. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  40999. changed = true;
  41000. }
  41001. if (defines["INSTANCES"] !== useInstances) {
  41002. defines["INSTANCES"] = useInstances;
  41003. changed = true;
  41004. }
  41005. if (changed) {
  41006. defines.markAsUnprocessed();
  41007. }
  41008. };
  41009. /**
  41010. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41011. * @param mesh The mesh containing the geometry data we will draw
  41012. * @param defines The defines to update
  41013. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41014. * @param useBones Precise whether bones should be used or not (override mesh info)
  41015. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41016. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41017. * @returns false if defines are considered not dirty and have not been checked
  41018. */
  41019. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41020. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41021. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41022. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41023. return false;
  41024. }
  41025. defines._normals = defines._needNormals;
  41026. defines._uvs = defines._needUVs;
  41027. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41028. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41029. defines["TANGENT"] = true;
  41030. }
  41031. if (defines._needUVs) {
  41032. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41033. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41034. }
  41035. else {
  41036. defines["UV1"] = false;
  41037. defines["UV2"] = false;
  41038. }
  41039. if (useVertexColor) {
  41040. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41041. defines["VERTEXCOLOR"] = hasVertexColors;
  41042. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41043. }
  41044. if (useBones) {
  41045. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41046. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41047. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41048. }
  41049. else {
  41050. defines["NUM_BONE_INFLUENCERS"] = 0;
  41051. defines["BonesPerMesh"] = 0;
  41052. }
  41053. }
  41054. if (useMorphTargets) {
  41055. var manager = mesh.morphTargetManager;
  41056. if (manager) {
  41057. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41058. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41059. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41060. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41061. }
  41062. else {
  41063. defines["MORPHTARGETS_TANGENT"] = false;
  41064. defines["MORPHTARGETS_NORMAL"] = false;
  41065. defines["MORPHTARGETS"] = false;
  41066. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41067. }
  41068. }
  41069. return true;
  41070. };
  41071. /**
  41072. * Prepares the defines related to the light information passed in parameter
  41073. * @param scene The scene we are intending to draw
  41074. * @param mesh The mesh the effect is compiling for
  41075. * @param defines The defines to update
  41076. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41077. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41078. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41079. * @returns true if normals will be required for the rest of the effect
  41080. */
  41081. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41082. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41083. if (disableLighting === void 0) { disableLighting = false; }
  41084. if (!defines._areLightsDirty) {
  41085. return defines._needNormals;
  41086. }
  41087. var lightIndex = 0;
  41088. var needNormals = false;
  41089. var needRebuild = false;
  41090. var lightmapMode = false;
  41091. var shadowEnabled = false;
  41092. var specularEnabled = false;
  41093. if (scene.lightsEnabled && !disableLighting) {
  41094. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41095. var light = _a[_i];
  41096. needNormals = true;
  41097. if (defines["LIGHT" + lightIndex] === undefined) {
  41098. needRebuild = true;
  41099. }
  41100. defines["LIGHT" + lightIndex] = true;
  41101. defines["SPOTLIGHT" + lightIndex] = false;
  41102. defines["HEMILIGHT" + lightIndex] = false;
  41103. defines["POINTLIGHT" + lightIndex] = false;
  41104. defines["DIRLIGHT" + lightIndex] = false;
  41105. var type;
  41106. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  41107. type = "SPOTLIGHT" + lightIndex;
  41108. var spotLight = light;
  41109. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  41110. }
  41111. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  41112. type = "HEMILIGHT" + lightIndex;
  41113. }
  41114. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  41115. type = "POINTLIGHT" + lightIndex;
  41116. }
  41117. else {
  41118. type = "DIRLIGHT" + lightIndex;
  41119. }
  41120. defines[type] = true;
  41121. // Specular
  41122. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41123. specularEnabled = true;
  41124. }
  41125. // Shadows
  41126. defines["SHADOW" + lightIndex] = false;
  41127. defines["SHADOWPCF" + lightIndex] = false;
  41128. defines["SHADOWPCSS" + lightIndex] = false;
  41129. defines["SHADOWPOISSON" + lightIndex] = false;
  41130. defines["SHADOWESM" + lightIndex] = false;
  41131. defines["SHADOWCUBE" + lightIndex] = false;
  41132. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41133. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41134. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41135. var shadowGenerator = light.getShadowGenerator();
  41136. if (shadowGenerator) {
  41137. shadowEnabled = true;
  41138. shadowGenerator.prepareDefines(defines, lightIndex);
  41139. }
  41140. }
  41141. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41142. lightmapMode = true;
  41143. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41144. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41145. }
  41146. else {
  41147. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41148. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41149. }
  41150. lightIndex++;
  41151. if (lightIndex === maxSimultaneousLights)
  41152. break;
  41153. }
  41154. }
  41155. defines["SPECULARTERM"] = specularEnabled;
  41156. defines["SHADOWS"] = shadowEnabled;
  41157. // Resetting all other lights if any
  41158. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41159. if (defines["LIGHT" + index] !== undefined) {
  41160. defines["LIGHT" + index] = false;
  41161. defines["HEMILIGHT" + lightIndex] = false;
  41162. defines["POINTLIGHT" + lightIndex] = false;
  41163. defines["DIRLIGHT" + lightIndex] = false;
  41164. defines["SPOTLIGHT" + lightIndex] = false;
  41165. defines["SHADOW" + lightIndex] = false;
  41166. }
  41167. }
  41168. var caps = scene.getEngine().getCaps();
  41169. if (defines["SHADOWFLOAT"] === undefined) {
  41170. needRebuild = true;
  41171. }
  41172. defines["SHADOWFLOAT"] = shadowEnabled &&
  41173. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41174. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41175. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41176. if (needRebuild) {
  41177. defines.rebuild();
  41178. }
  41179. return needNormals;
  41180. };
  41181. /**
  41182. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41183. * that won t be acctive due to defines being turned off.
  41184. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41185. * @param samplersList The samplers list
  41186. * @param defines The defines helping in the list generation
  41187. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41188. */
  41189. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41190. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41191. var uniformsList;
  41192. var uniformBuffersList = null;
  41193. if (uniformsListOrOptions.uniformsNames) {
  41194. var options = uniformsListOrOptions;
  41195. uniformsList = options.uniformsNames;
  41196. uniformBuffersList = options.uniformBuffersNames;
  41197. samplersList = options.samplers;
  41198. defines = options.defines;
  41199. maxSimultaneousLights = options.maxSimultaneousLights;
  41200. }
  41201. else {
  41202. uniformsList = uniformsListOrOptions;
  41203. if (!samplersList) {
  41204. samplersList = [];
  41205. }
  41206. }
  41207. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41208. if (!defines["LIGHT" + lightIndex]) {
  41209. break;
  41210. }
  41211. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41212. if (uniformBuffersList) {
  41213. uniformBuffersList.push("Light" + lightIndex);
  41214. }
  41215. samplersList.push("shadowSampler" + lightIndex);
  41216. samplersList.push("depthSampler" + lightIndex);
  41217. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41218. samplersList.push("projectionLightSampler" + lightIndex);
  41219. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41220. }
  41221. }
  41222. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41223. uniformsList.push("morphTargetInfluences");
  41224. }
  41225. };
  41226. /**
  41227. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41228. * @param defines The defines to update while falling back
  41229. * @param fallbacks The authorized effect fallbacks
  41230. * @param maxSimultaneousLights The maximum number of lights allowed
  41231. * @param rank the current rank of the Effect
  41232. * @returns The newly affected rank
  41233. */
  41234. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41235. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41236. if (rank === void 0) { rank = 0; }
  41237. var lightFallbackRank = 0;
  41238. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41239. if (!defines["LIGHT" + lightIndex]) {
  41240. break;
  41241. }
  41242. if (lightIndex > 0) {
  41243. lightFallbackRank = rank + lightIndex;
  41244. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41245. }
  41246. if (!defines["SHADOWS"]) {
  41247. if (defines["SHADOW" + lightIndex]) {
  41248. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41249. }
  41250. if (defines["SHADOWPCF" + lightIndex]) {
  41251. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41252. }
  41253. if (defines["SHADOWPCSS" + lightIndex]) {
  41254. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41255. }
  41256. if (defines["SHADOWPOISSON" + lightIndex]) {
  41257. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41258. }
  41259. if (defines["SHADOWESM" + lightIndex]) {
  41260. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41261. }
  41262. }
  41263. }
  41264. return lightFallbackRank++;
  41265. };
  41266. /**
  41267. * Prepares the list of attributes required for morph targets according to the effect defines.
  41268. * @param attribs The current list of supported attribs
  41269. * @param mesh The mesh to prepare the morph targets attributes for
  41270. * @param defines The current Defines of the effect
  41271. */
  41272. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41273. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41274. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41275. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41276. var manager = mesh.morphTargetManager;
  41277. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41278. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41279. for (var index = 0; index < influencers; index++) {
  41280. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41281. if (normal) {
  41282. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41283. }
  41284. if (tangent) {
  41285. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41286. }
  41287. if (attribs.length > maxAttributesCount) {
  41288. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41289. }
  41290. }
  41291. }
  41292. };
  41293. /**
  41294. * Prepares the list of attributes required for bones according to the effect defines.
  41295. * @param attribs The current list of supported attribs
  41296. * @param mesh The mesh to prepare the bones attributes for
  41297. * @param defines The current Defines of the effect
  41298. * @param fallbacks The current efffect fallback strategy
  41299. */
  41300. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41301. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41302. fallbacks.addCPUSkinningFallback(0, mesh);
  41303. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41304. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41305. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41306. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41307. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41308. }
  41309. }
  41310. };
  41311. /**
  41312. * Prepares the list of attributes required for instances according to the effect defines.
  41313. * @param attribs The current list of supported attribs
  41314. * @param defines The current Defines of the effect
  41315. */
  41316. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41317. if (defines["INSTANCES"]) {
  41318. attribs.push("world0");
  41319. attribs.push("world1");
  41320. attribs.push("world2");
  41321. attribs.push("world3");
  41322. }
  41323. };
  41324. /**
  41325. * Binds the light shadow information to the effect for the given mesh.
  41326. * @param light The light containing the generator
  41327. * @param scene The scene the lights belongs to
  41328. * @param mesh The mesh we are binding the information to render
  41329. * @param lightIndex The light index in the effect used to render the mesh
  41330. * @param effect The effect we are binding the data to
  41331. */
  41332. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41333. if (light.shadowEnabled && mesh.receiveShadows) {
  41334. var shadowGenerator = light.getShadowGenerator();
  41335. if (shadowGenerator) {
  41336. shadowGenerator.bindShadowLight(lightIndex, effect);
  41337. }
  41338. }
  41339. };
  41340. /**
  41341. * Binds the light information to the effect.
  41342. * @param light The light containing the generator
  41343. * @param effect The effect we are binding the data to
  41344. * @param lightIndex The light index in the effect used to render
  41345. */
  41346. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41347. light.transferToEffect(effect, lightIndex + "");
  41348. };
  41349. /**
  41350. * Binds the lights information from the scene to the effect for the given mesh.
  41351. * @param scene The scene the lights belongs to
  41352. * @param mesh The mesh we are binding the information to render
  41353. * @param effect The effect we are binding the data to
  41354. * @param defines The generated defines for the effect
  41355. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41356. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41357. */
  41358. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41359. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41360. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41361. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41362. for (var i = 0; i < len; i++) {
  41363. var light = mesh._lightSources[i];
  41364. var iAsString = i.toString();
  41365. var scaledIntensity = light.getScaledIntensity();
  41366. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41367. MaterialHelper.BindLightProperties(light, effect, i);
  41368. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41369. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41370. if (defines["SPECULARTERM"]) {
  41371. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41372. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41373. }
  41374. // Shadows
  41375. if (scene.shadowsEnabled) {
  41376. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41377. }
  41378. light._uniformBuffer.update();
  41379. }
  41380. };
  41381. /**
  41382. * Binds the fog information from the scene to the effect for the given mesh.
  41383. * @param scene The scene the lights belongs to
  41384. * @param mesh The mesh we are binding the information to render
  41385. * @param effect The effect we are binding the data to
  41386. */
  41387. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41388. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41389. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41390. effect.setColor3("vFogColor", scene.fogColor);
  41391. }
  41392. };
  41393. /**
  41394. * Binds the bones information from the mesh to the effect.
  41395. * @param mesh The mesh we are binding the information to render
  41396. * @param effect The effect we are binding the data to
  41397. */
  41398. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41399. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41400. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41401. if (matrices && effect) {
  41402. effect.setMatrices("mBones", matrices);
  41403. }
  41404. }
  41405. };
  41406. /**
  41407. * Binds the morph targets information from the mesh to the effect.
  41408. * @param abstractMesh The mesh we are binding the information to render
  41409. * @param effect The effect we are binding the data to
  41410. */
  41411. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41412. var manager = abstractMesh.morphTargetManager;
  41413. if (!abstractMesh || !manager) {
  41414. return;
  41415. }
  41416. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41417. };
  41418. /**
  41419. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41420. * @param defines The generated defines used in the effect
  41421. * @param effect The effect we are binding the data to
  41422. * @param scene The scene we are willing to render with logarithmic scale for
  41423. */
  41424. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41425. if (defines["LOGARITHMICDEPTH"]) {
  41426. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41427. }
  41428. };
  41429. /**
  41430. * Binds the clip plane information from the scene to the effect.
  41431. * @param scene The scene the clip plane information are extracted from
  41432. * @param effect The effect we are binding the data to
  41433. */
  41434. MaterialHelper.BindClipPlane = function (effect, scene) {
  41435. if (scene.clipPlane) {
  41436. var clipPlane = scene.clipPlane;
  41437. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41438. }
  41439. };
  41440. return MaterialHelper;
  41441. }());
  41442. BABYLON.MaterialHelper = MaterialHelper;
  41443. })(BABYLON || (BABYLON = {}));
  41444. //# sourceMappingURL=babylon.materialHelper.js.map
  41445. "use strict";
  41446. var BABYLON;
  41447. (function (BABYLON) {
  41448. var PushMaterial = /** @class */ (function (_super) {
  41449. __extends(PushMaterial, _super);
  41450. function PushMaterial(name, scene) {
  41451. var _this = _super.call(this, name, scene) || this;
  41452. _this._normalMatrix = new BABYLON.Matrix();
  41453. _this.storeEffectOnSubMeshes = true;
  41454. return _this;
  41455. }
  41456. PushMaterial.prototype.getEffect = function () {
  41457. return this._activeEffect;
  41458. };
  41459. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41460. if (!mesh) {
  41461. return false;
  41462. }
  41463. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41464. return true;
  41465. }
  41466. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41467. };
  41468. /**
  41469. * Binds the given world matrix to the active effect
  41470. *
  41471. * @param world the matrix to bind
  41472. */
  41473. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41474. this._activeEffect.setMatrix("world", world);
  41475. };
  41476. /**
  41477. * Binds the given normal matrix to the active effect
  41478. *
  41479. * @param normalMatrix the matrix to bind
  41480. */
  41481. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41482. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41483. };
  41484. PushMaterial.prototype.bind = function (world, mesh) {
  41485. if (!mesh) {
  41486. return;
  41487. }
  41488. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41489. };
  41490. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41491. if (effect === void 0) { effect = null; }
  41492. _super.prototype._afterBind.call(this, mesh);
  41493. this.getScene()._cachedEffect = effect;
  41494. };
  41495. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41496. if (visibility === void 0) { visibility = 1; }
  41497. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41498. };
  41499. return PushMaterial;
  41500. }(BABYLON.Material));
  41501. BABYLON.PushMaterial = PushMaterial;
  41502. })(BABYLON || (BABYLON = {}));
  41503. //# sourceMappingURL=babylon.pushMaterial.js.map
  41504. "use strict";
  41505. var BABYLON;
  41506. (function (BABYLON) {
  41507. /** @ignore */
  41508. var StandardMaterialDefines = /** @class */ (function (_super) {
  41509. __extends(StandardMaterialDefines, _super);
  41510. function StandardMaterialDefines() {
  41511. var _this = _super.call(this) || this;
  41512. _this.MAINUV1 = false;
  41513. _this.MAINUV2 = false;
  41514. _this.DIFFUSE = false;
  41515. _this.DIFFUSEDIRECTUV = 0;
  41516. _this.AMBIENT = false;
  41517. _this.AMBIENTDIRECTUV = 0;
  41518. _this.OPACITY = false;
  41519. _this.OPACITYDIRECTUV = 0;
  41520. _this.OPACITYRGB = false;
  41521. _this.REFLECTION = false;
  41522. _this.EMISSIVE = false;
  41523. _this.EMISSIVEDIRECTUV = 0;
  41524. _this.SPECULAR = false;
  41525. _this.SPECULARDIRECTUV = 0;
  41526. _this.BUMP = false;
  41527. _this.BUMPDIRECTUV = 0;
  41528. _this.PARALLAX = false;
  41529. _this.PARALLAXOCCLUSION = false;
  41530. _this.SPECULAROVERALPHA = false;
  41531. _this.CLIPPLANE = false;
  41532. _this.ALPHATEST = false;
  41533. _this.DEPTHPREPASS = false;
  41534. _this.ALPHAFROMDIFFUSE = false;
  41535. _this.POINTSIZE = false;
  41536. _this.FOG = false;
  41537. _this.SPECULARTERM = false;
  41538. _this.DIFFUSEFRESNEL = false;
  41539. _this.OPACITYFRESNEL = false;
  41540. _this.REFLECTIONFRESNEL = false;
  41541. _this.REFRACTIONFRESNEL = false;
  41542. _this.EMISSIVEFRESNEL = false;
  41543. _this.FRESNEL = false;
  41544. _this.NORMAL = false;
  41545. _this.UV1 = false;
  41546. _this.UV2 = false;
  41547. _this.VERTEXCOLOR = false;
  41548. _this.VERTEXALPHA = false;
  41549. _this.NUM_BONE_INFLUENCERS = 0;
  41550. _this.BonesPerMesh = 0;
  41551. _this.INSTANCES = false;
  41552. _this.GLOSSINESS = false;
  41553. _this.ROUGHNESS = false;
  41554. _this.EMISSIVEASILLUMINATION = false;
  41555. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41556. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41557. _this.LIGHTMAP = false;
  41558. _this.LIGHTMAPDIRECTUV = 0;
  41559. _this.OBJECTSPACE_NORMALMAP = false;
  41560. _this.USELIGHTMAPASSHADOWMAP = false;
  41561. _this.REFLECTIONMAP_3D = false;
  41562. _this.REFLECTIONMAP_SPHERICAL = false;
  41563. _this.REFLECTIONMAP_PLANAR = false;
  41564. _this.REFLECTIONMAP_CUBIC = false;
  41565. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41566. _this.REFLECTIONMAP_PROJECTION = false;
  41567. _this.REFLECTIONMAP_SKYBOX = false;
  41568. _this.REFLECTIONMAP_EXPLICIT = false;
  41569. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41570. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41571. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41572. _this.INVERTCUBICMAP = false;
  41573. _this.LOGARITHMICDEPTH = false;
  41574. _this.REFRACTION = false;
  41575. _this.REFRACTIONMAP_3D = false;
  41576. _this.REFLECTIONOVERALPHA = false;
  41577. _this.TWOSIDEDLIGHTING = false;
  41578. _this.SHADOWFLOAT = false;
  41579. _this.MORPHTARGETS = false;
  41580. _this.MORPHTARGETS_NORMAL = false;
  41581. _this.MORPHTARGETS_TANGENT = false;
  41582. _this.NUM_MORPH_INFLUENCERS = 0;
  41583. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41584. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41585. _this.IMAGEPROCESSING = false;
  41586. _this.VIGNETTE = false;
  41587. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41588. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41589. _this.TONEMAPPING = false;
  41590. _this.CONTRAST = false;
  41591. _this.COLORCURVES = false;
  41592. _this.COLORGRADING = false;
  41593. _this.COLORGRADING3D = false;
  41594. _this.SAMPLER3DGREENDEPTH = false;
  41595. _this.SAMPLER3DBGRMAP = false;
  41596. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41597. _this.EXPOSURE = false;
  41598. _this.rebuild();
  41599. return _this;
  41600. }
  41601. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41602. var modes = [
  41603. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41604. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41605. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41606. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41607. ];
  41608. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41609. var mode = modes_1[_i];
  41610. this[mode] = (mode === modeToEnable);
  41611. }
  41612. };
  41613. return StandardMaterialDefines;
  41614. }(BABYLON.MaterialDefines));
  41615. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41616. var StandardMaterial = /** @class */ (function (_super) {
  41617. __extends(StandardMaterial, _super);
  41618. function StandardMaterial(name, scene) {
  41619. var _this = _super.call(this, name, scene) || this;
  41620. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41621. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41622. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41623. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41624. _this.specularPower = 64;
  41625. _this._useAlphaFromDiffuseTexture = false;
  41626. _this._useEmissiveAsIllumination = false;
  41627. _this._linkEmissiveWithDiffuse = false;
  41628. _this._useSpecularOverAlpha = false;
  41629. _this._useReflectionOverAlpha = false;
  41630. _this._disableLighting = false;
  41631. _this._useObjectSpaceNormalMap = false;
  41632. _this._useParallax = false;
  41633. _this._useParallaxOcclusion = false;
  41634. _this.parallaxScaleBias = 0.05;
  41635. _this._roughness = 0;
  41636. _this.indexOfRefraction = 0.98;
  41637. _this.invertRefractionY = true;
  41638. _this._useLightmapAsShadowmap = false;
  41639. _this._useReflectionFresnelFromSpecular = false;
  41640. _this._useGlossinessFromSpecularMapAlpha = false;
  41641. _this._maxSimultaneousLights = 4;
  41642. /**
  41643. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41644. */
  41645. _this._invertNormalMapX = false;
  41646. /**
  41647. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41648. */
  41649. _this._invertNormalMapY = false;
  41650. /**
  41651. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41652. */
  41653. _this._twoSidedLighting = false;
  41654. _this._renderTargets = new BABYLON.SmartArray(16);
  41655. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41656. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41657. // Setup the default processing configuration to the scene.
  41658. _this._attachImageProcessingConfiguration(null);
  41659. _this.getRenderTargetTextures = function () {
  41660. _this._renderTargets.reset();
  41661. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41662. _this._renderTargets.push(_this._reflectionTexture);
  41663. }
  41664. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41665. _this._renderTargets.push(_this._refractionTexture);
  41666. }
  41667. return _this._renderTargets;
  41668. };
  41669. return _this;
  41670. }
  41671. ;
  41672. ;
  41673. ;
  41674. ;
  41675. ;
  41676. ;
  41677. ;
  41678. ;
  41679. ;
  41680. ;
  41681. ;
  41682. ;
  41683. ;
  41684. ;
  41685. ;
  41686. ;
  41687. ;
  41688. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41689. /**
  41690. * Gets the image processing configuration used either in this material.
  41691. */
  41692. get: function () {
  41693. return this._imageProcessingConfiguration;
  41694. },
  41695. /**
  41696. * Sets the Default image processing configuration used either in the this material.
  41697. *
  41698. * If sets to null, the scene one is in use.
  41699. */
  41700. set: function (value) {
  41701. this._attachImageProcessingConfiguration(value);
  41702. // Ensure the effect will be rebuilt.
  41703. this._markAllSubMeshesAsTexturesDirty();
  41704. },
  41705. enumerable: true,
  41706. configurable: true
  41707. });
  41708. /**
  41709. * Attaches a new image processing configuration to the Standard Material.
  41710. * @param configuration
  41711. */
  41712. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41713. var _this = this;
  41714. if (configuration === this._imageProcessingConfiguration) {
  41715. return;
  41716. }
  41717. // Detaches observer.
  41718. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41719. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41720. }
  41721. // Pick the scene configuration if needed.
  41722. if (!configuration) {
  41723. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41724. }
  41725. else {
  41726. this._imageProcessingConfiguration = configuration;
  41727. }
  41728. // Attaches observer.
  41729. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41730. _this._markAllSubMeshesAsImageProcessingDirty();
  41731. });
  41732. };
  41733. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  41734. /**
  41735. * Gets wether the color curves effect is enabled.
  41736. */
  41737. get: function () {
  41738. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41739. },
  41740. /**
  41741. * Sets wether the color curves effect is enabled.
  41742. */
  41743. set: function (value) {
  41744. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41745. },
  41746. enumerable: true,
  41747. configurable: true
  41748. });
  41749. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  41750. /**
  41751. * Gets wether the color grading effect is enabled.
  41752. */
  41753. get: function () {
  41754. return this.imageProcessingConfiguration.colorGradingEnabled;
  41755. },
  41756. /**
  41757. * Gets wether the color grading effect is enabled.
  41758. */
  41759. set: function (value) {
  41760. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41761. },
  41762. enumerable: true,
  41763. configurable: true
  41764. });
  41765. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  41766. /**
  41767. * Gets wether tonemapping is enabled or not.
  41768. */
  41769. get: function () {
  41770. return this._imageProcessingConfiguration.toneMappingEnabled;
  41771. },
  41772. /**
  41773. * Sets wether tonemapping is enabled or not
  41774. */
  41775. set: function (value) {
  41776. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41777. },
  41778. enumerable: true,
  41779. configurable: true
  41780. });
  41781. ;
  41782. ;
  41783. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  41784. /**
  41785. * The camera exposure used on this material.
  41786. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41787. * This corresponds to a photographic exposure.
  41788. */
  41789. get: function () {
  41790. return this._imageProcessingConfiguration.exposure;
  41791. },
  41792. /**
  41793. * The camera exposure used on this material.
  41794. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41795. * This corresponds to a photographic exposure.
  41796. */
  41797. set: function (value) {
  41798. this._imageProcessingConfiguration.exposure = value;
  41799. },
  41800. enumerable: true,
  41801. configurable: true
  41802. });
  41803. ;
  41804. ;
  41805. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  41806. /**
  41807. * Gets The camera contrast used on this material.
  41808. */
  41809. get: function () {
  41810. return this._imageProcessingConfiguration.contrast;
  41811. },
  41812. /**
  41813. * Sets The camera contrast used on this material.
  41814. */
  41815. set: function (value) {
  41816. this._imageProcessingConfiguration.contrast = value;
  41817. },
  41818. enumerable: true,
  41819. configurable: true
  41820. });
  41821. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  41822. /**
  41823. * Gets the Color Grading 2D Lookup Texture.
  41824. */
  41825. get: function () {
  41826. return this._imageProcessingConfiguration.colorGradingTexture;
  41827. },
  41828. /**
  41829. * Sets the Color Grading 2D Lookup Texture.
  41830. */
  41831. set: function (value) {
  41832. this._imageProcessingConfiguration.colorGradingTexture = value;
  41833. },
  41834. enumerable: true,
  41835. configurable: true
  41836. });
  41837. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  41838. /**
  41839. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41840. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41841. * 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;
  41842. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41843. */
  41844. get: function () {
  41845. return this._imageProcessingConfiguration.colorCurves;
  41846. },
  41847. /**
  41848. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41849. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41850. * 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;
  41851. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41852. */
  41853. set: function (value) {
  41854. this._imageProcessingConfiguration.colorCurves = value;
  41855. },
  41856. enumerable: true,
  41857. configurable: true
  41858. });
  41859. StandardMaterial.prototype.getClassName = function () {
  41860. return "StandardMaterial";
  41861. };
  41862. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  41863. get: function () {
  41864. return this._useLogarithmicDepth;
  41865. },
  41866. set: function (value) {
  41867. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41868. this._markAllSubMeshesAsMiscDirty();
  41869. },
  41870. enumerable: true,
  41871. configurable: true
  41872. });
  41873. StandardMaterial.prototype.needAlphaBlending = function () {
  41874. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  41875. };
  41876. StandardMaterial.prototype.needAlphaTesting = function () {
  41877. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  41878. };
  41879. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  41880. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  41881. };
  41882. StandardMaterial.prototype.getAlphaTestTexture = function () {
  41883. return this._diffuseTexture;
  41884. };
  41885. /**
  41886. * Child classes can use it to update shaders
  41887. */
  41888. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41889. if (useInstances === void 0) { useInstances = false; }
  41890. if (subMesh.effect && this.isFrozen) {
  41891. if (this._wasPreviouslyReady && subMesh.effect) {
  41892. return true;
  41893. }
  41894. }
  41895. if (!subMesh._materialDefines) {
  41896. subMesh._materialDefines = new StandardMaterialDefines();
  41897. }
  41898. var scene = this.getScene();
  41899. var defines = subMesh._materialDefines;
  41900. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41901. if (defines._renderId === scene.getRenderId()) {
  41902. return true;
  41903. }
  41904. }
  41905. var engine = scene.getEngine();
  41906. // Lights
  41907. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41908. // Textures
  41909. if (defines._areTexturesDirty) {
  41910. defines._needUVs = false;
  41911. defines.MAINUV1 = false;
  41912. defines.MAINUV2 = false;
  41913. if (scene.texturesEnabled) {
  41914. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  41915. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  41916. return false;
  41917. }
  41918. else {
  41919. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  41920. }
  41921. }
  41922. else {
  41923. defines.DIFFUSE = false;
  41924. }
  41925. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  41926. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41927. return false;
  41928. }
  41929. else {
  41930. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41931. }
  41932. }
  41933. else {
  41934. defines.AMBIENT = false;
  41935. }
  41936. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  41937. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41938. return false;
  41939. }
  41940. else {
  41941. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41942. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41943. }
  41944. }
  41945. else {
  41946. defines.OPACITY = false;
  41947. }
  41948. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  41949. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  41950. return false;
  41951. }
  41952. else {
  41953. defines._needNormals = true;
  41954. defines.REFLECTION = true;
  41955. defines.ROUGHNESS = (this._roughness > 0);
  41956. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  41957. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  41958. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  41959. switch (this._reflectionTexture.coordinatesMode) {
  41960. case BABYLON.Texture.CUBIC_MODE:
  41961. case BABYLON.Texture.INVCUBIC_MODE:
  41962. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  41963. break;
  41964. case BABYLON.Texture.EXPLICIT_MODE:
  41965. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  41966. break;
  41967. case BABYLON.Texture.PLANAR_MODE:
  41968. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  41969. break;
  41970. case BABYLON.Texture.PROJECTION_MODE:
  41971. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  41972. break;
  41973. case BABYLON.Texture.SKYBOX_MODE:
  41974. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  41975. break;
  41976. case BABYLON.Texture.SPHERICAL_MODE:
  41977. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  41978. break;
  41979. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41980. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  41981. break;
  41982. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41983. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  41984. break;
  41985. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41986. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  41987. break;
  41988. }
  41989. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  41990. }
  41991. }
  41992. else {
  41993. defines.REFLECTION = false;
  41994. }
  41995. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  41996. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41997. return false;
  41998. }
  41999. else {
  42000. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42001. }
  42002. }
  42003. else {
  42004. defines.EMISSIVE = false;
  42005. }
  42006. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42007. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42008. return false;
  42009. }
  42010. else {
  42011. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42012. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42013. }
  42014. }
  42015. else {
  42016. defines.LIGHTMAP = false;
  42017. }
  42018. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42019. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42020. return false;
  42021. }
  42022. else {
  42023. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42024. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42025. }
  42026. }
  42027. else {
  42028. defines.SPECULAR = false;
  42029. }
  42030. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42031. // Bump texure can not be not blocking.
  42032. if (!this._bumpTexture.isReady()) {
  42033. return false;
  42034. }
  42035. else {
  42036. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42037. defines.PARALLAX = this._useParallax;
  42038. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42039. }
  42040. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42041. }
  42042. else {
  42043. defines.BUMP = false;
  42044. }
  42045. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42046. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42047. return false;
  42048. }
  42049. else {
  42050. defines._needUVs = true;
  42051. defines.REFRACTION = true;
  42052. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42053. }
  42054. }
  42055. else {
  42056. defines.REFRACTION = false;
  42057. }
  42058. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42059. }
  42060. else {
  42061. defines.DIFFUSE = false;
  42062. defines.AMBIENT = false;
  42063. defines.OPACITY = false;
  42064. defines.REFLECTION = false;
  42065. defines.EMISSIVE = false;
  42066. defines.LIGHTMAP = false;
  42067. defines.BUMP = false;
  42068. defines.REFRACTION = false;
  42069. }
  42070. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42071. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42072. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42073. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42074. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42075. }
  42076. if (defines._areImageProcessingDirty) {
  42077. if (!this._imageProcessingConfiguration.isReady()) {
  42078. return false;
  42079. }
  42080. this._imageProcessingConfiguration.prepareDefines(defines);
  42081. }
  42082. if (defines._areFresnelDirty) {
  42083. if (StandardMaterial.FresnelEnabled) {
  42084. // Fresnel
  42085. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42086. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42087. this._reflectionFresnelParameters) {
  42088. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42089. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42090. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42091. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42092. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42093. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42094. defines._needNormals = true;
  42095. defines.FRESNEL = true;
  42096. }
  42097. }
  42098. else {
  42099. defines.FRESNEL = false;
  42100. }
  42101. }
  42102. // Misc.
  42103. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42104. // Attribs
  42105. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42106. // Values that need to be evaluated on every frame
  42107. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42108. // Get correct effect
  42109. if (defines.isDirty) {
  42110. defines.markAsProcessed();
  42111. scene.resetCachedMaterial();
  42112. // Fallbacks
  42113. var fallbacks = new BABYLON.EffectFallbacks();
  42114. if (defines.REFLECTION) {
  42115. fallbacks.addFallback(0, "REFLECTION");
  42116. }
  42117. if (defines.SPECULAR) {
  42118. fallbacks.addFallback(0, "SPECULAR");
  42119. }
  42120. if (defines.BUMP) {
  42121. fallbacks.addFallback(0, "BUMP");
  42122. }
  42123. if (defines.PARALLAX) {
  42124. fallbacks.addFallback(1, "PARALLAX");
  42125. }
  42126. if (defines.PARALLAXOCCLUSION) {
  42127. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42128. }
  42129. if (defines.SPECULAROVERALPHA) {
  42130. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42131. }
  42132. if (defines.FOG) {
  42133. fallbacks.addFallback(1, "FOG");
  42134. }
  42135. if (defines.POINTSIZE) {
  42136. fallbacks.addFallback(0, "POINTSIZE");
  42137. }
  42138. if (defines.LOGARITHMICDEPTH) {
  42139. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42140. }
  42141. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42142. if (defines.SPECULARTERM) {
  42143. fallbacks.addFallback(0, "SPECULARTERM");
  42144. }
  42145. if (defines.DIFFUSEFRESNEL) {
  42146. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42147. }
  42148. if (defines.OPACITYFRESNEL) {
  42149. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42150. }
  42151. if (defines.REFLECTIONFRESNEL) {
  42152. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42153. }
  42154. if (defines.EMISSIVEFRESNEL) {
  42155. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42156. }
  42157. if (defines.FRESNEL) {
  42158. fallbacks.addFallback(4, "FRESNEL");
  42159. }
  42160. //Attributes
  42161. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42162. if (defines.NORMAL) {
  42163. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42164. }
  42165. if (defines.UV1) {
  42166. attribs.push(BABYLON.VertexBuffer.UVKind);
  42167. }
  42168. if (defines.UV2) {
  42169. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42170. }
  42171. if (defines.VERTEXCOLOR) {
  42172. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42173. }
  42174. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42175. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42176. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42177. var shaderName = "default";
  42178. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42179. "vFogInfos", "vFogColor", "pointSize",
  42180. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42181. "mBones",
  42182. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42183. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42184. "vReflectionPosition", "vReflectionSize",
  42185. "logarithmicDepthConstant", "vTangentSpaceParams"
  42186. ];
  42187. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42188. var uniformBuffers = ["Material", "Scene"];
  42189. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42190. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42191. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42192. uniformsNames: uniforms,
  42193. uniformBuffersNames: uniformBuffers,
  42194. samplers: samplers,
  42195. defines: defines,
  42196. maxSimultaneousLights: this._maxSimultaneousLights
  42197. });
  42198. if (this.customShaderNameResolve) {
  42199. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42200. }
  42201. var join = defines.toString();
  42202. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42203. attributes: attribs,
  42204. uniformsNames: uniforms,
  42205. uniformBuffersNames: uniformBuffers,
  42206. samplers: samplers,
  42207. defines: join,
  42208. fallbacks: fallbacks,
  42209. onCompiled: this.onCompiled,
  42210. onError: this.onError,
  42211. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42212. }, engine), defines);
  42213. this.buildUniformLayout();
  42214. }
  42215. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42216. return false;
  42217. }
  42218. defines._renderId = scene.getRenderId();
  42219. this._wasPreviouslyReady = true;
  42220. return true;
  42221. };
  42222. StandardMaterial.prototype.buildUniformLayout = function () {
  42223. // Order is important !
  42224. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42225. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42226. this._uniformBuffer.addUniform("opacityParts", 4);
  42227. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42228. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42229. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42230. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42231. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42232. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42233. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42234. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42235. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42236. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42237. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42238. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42239. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42240. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42241. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42242. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42243. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42244. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42245. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42246. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42247. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42248. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42249. this._uniformBuffer.addUniform("specularMatrix", 16);
  42250. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42251. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42252. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42253. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42254. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42255. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42256. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42257. this._uniformBuffer.addUniform("pointSize", 1);
  42258. this._uniformBuffer.create();
  42259. };
  42260. StandardMaterial.prototype.unbind = function () {
  42261. if (this._activeEffect) {
  42262. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42263. this._activeEffect.setTexture("reflection2DSampler", null);
  42264. }
  42265. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42266. this._activeEffect.setTexture("refraction2DSampler", null);
  42267. }
  42268. }
  42269. _super.prototype.unbind.call(this);
  42270. };
  42271. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42272. var scene = this.getScene();
  42273. var defines = subMesh._materialDefines;
  42274. if (!defines) {
  42275. return;
  42276. }
  42277. var effect = subMesh.effect;
  42278. if (!effect) {
  42279. return;
  42280. }
  42281. this._activeEffect = effect;
  42282. // Matrices
  42283. this.bindOnlyWorldMatrix(world);
  42284. // Normal Matrix
  42285. if (defines.OBJECTSPACE_NORMALMAP) {
  42286. world.toNormalMatrix(this._normalMatrix);
  42287. this.bindOnlyNormalMatrix(this._normalMatrix);
  42288. }
  42289. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42290. // Bones
  42291. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42292. if (mustRebind) {
  42293. this._uniformBuffer.bindToEffect(effect, "Material");
  42294. this.bindViewProjection(effect);
  42295. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42296. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42297. // Fresnel
  42298. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42299. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42300. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42301. }
  42302. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42303. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42304. }
  42305. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42306. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42307. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42308. }
  42309. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42310. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42311. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42312. }
  42313. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42314. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42315. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42316. }
  42317. }
  42318. // Textures
  42319. if (scene.texturesEnabled) {
  42320. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42321. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42322. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42323. }
  42324. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42325. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42326. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42327. }
  42328. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42329. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42330. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42331. }
  42332. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42333. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42334. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42335. if (this._reflectionTexture.boundingBoxSize) {
  42336. var cubeTexture = this._reflectionTexture;
  42337. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42338. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42339. }
  42340. }
  42341. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42342. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42343. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42344. }
  42345. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42346. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42347. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42348. }
  42349. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42350. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42351. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42352. }
  42353. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42354. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42355. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42356. if (scene._mirroredCameraPosition) {
  42357. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42358. }
  42359. else {
  42360. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42361. }
  42362. }
  42363. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42364. var depth = 1.0;
  42365. if (!this._refractionTexture.isCube) {
  42366. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42367. if (this._refractionTexture.depth) {
  42368. depth = this._refractionTexture.depth;
  42369. }
  42370. }
  42371. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42372. }
  42373. }
  42374. // Point size
  42375. if (this.pointsCloud) {
  42376. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42377. }
  42378. if (defines.SPECULARTERM) {
  42379. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42380. }
  42381. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42382. // Diffuse
  42383. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42384. }
  42385. // Textures
  42386. if (scene.texturesEnabled) {
  42387. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42388. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42389. }
  42390. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42391. effect.setTexture("ambientSampler", this._ambientTexture);
  42392. }
  42393. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42394. effect.setTexture("opacitySampler", this._opacityTexture);
  42395. }
  42396. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42397. if (this._reflectionTexture.isCube) {
  42398. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42399. }
  42400. else {
  42401. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42402. }
  42403. }
  42404. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42405. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42406. }
  42407. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42408. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42409. }
  42410. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42411. effect.setTexture("specularSampler", this._specularTexture);
  42412. }
  42413. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42414. effect.setTexture("bumpSampler", this._bumpTexture);
  42415. }
  42416. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42417. var depth = 1.0;
  42418. if (this._refractionTexture.isCube) {
  42419. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42420. }
  42421. else {
  42422. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42423. }
  42424. }
  42425. }
  42426. // Clip plane
  42427. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42428. // Colors
  42429. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42430. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42431. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42432. }
  42433. if (mustRebind || !this.isFrozen) {
  42434. // Lights
  42435. if (scene.lightsEnabled && !this._disableLighting) {
  42436. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42437. }
  42438. // View
  42439. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42440. this.bindView(effect);
  42441. }
  42442. // Fog
  42443. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42444. // Morph targets
  42445. if (defines.NUM_MORPH_INFLUENCERS) {
  42446. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42447. }
  42448. // Log. depth
  42449. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42450. // image processing
  42451. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  42452. this._imageProcessingConfiguration.bind(this._activeEffect);
  42453. }
  42454. }
  42455. this._uniformBuffer.update();
  42456. this._afterBind(mesh, this._activeEffect);
  42457. };
  42458. StandardMaterial.prototype.getAnimatables = function () {
  42459. var results = [];
  42460. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42461. results.push(this._diffuseTexture);
  42462. }
  42463. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42464. results.push(this._ambientTexture);
  42465. }
  42466. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42467. results.push(this._opacityTexture);
  42468. }
  42469. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42470. results.push(this._reflectionTexture);
  42471. }
  42472. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42473. results.push(this._emissiveTexture);
  42474. }
  42475. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42476. results.push(this._specularTexture);
  42477. }
  42478. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42479. results.push(this._bumpTexture);
  42480. }
  42481. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42482. results.push(this._lightmapTexture);
  42483. }
  42484. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42485. results.push(this._refractionTexture);
  42486. }
  42487. return results;
  42488. };
  42489. StandardMaterial.prototype.getActiveTextures = function () {
  42490. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42491. if (this._diffuseTexture) {
  42492. activeTextures.push(this._diffuseTexture);
  42493. }
  42494. if (this._ambientTexture) {
  42495. activeTextures.push(this._ambientTexture);
  42496. }
  42497. if (this._opacityTexture) {
  42498. activeTextures.push(this._opacityTexture);
  42499. }
  42500. if (this._reflectionTexture) {
  42501. activeTextures.push(this._reflectionTexture);
  42502. }
  42503. if (this._emissiveTexture) {
  42504. activeTextures.push(this._emissiveTexture);
  42505. }
  42506. if (this._specularTexture) {
  42507. activeTextures.push(this._specularTexture);
  42508. }
  42509. if (this._bumpTexture) {
  42510. activeTextures.push(this._bumpTexture);
  42511. }
  42512. if (this._lightmapTexture) {
  42513. activeTextures.push(this._lightmapTexture);
  42514. }
  42515. if (this._refractionTexture) {
  42516. activeTextures.push(this._refractionTexture);
  42517. }
  42518. return activeTextures;
  42519. };
  42520. StandardMaterial.prototype.hasTexture = function (texture) {
  42521. if (_super.prototype.hasTexture.call(this, texture)) {
  42522. return true;
  42523. }
  42524. if (this._diffuseTexture === texture) {
  42525. return true;
  42526. }
  42527. if (this._ambientTexture === texture) {
  42528. return true;
  42529. }
  42530. if (this._opacityTexture === texture) {
  42531. return true;
  42532. }
  42533. if (this._reflectionTexture === texture) {
  42534. return true;
  42535. }
  42536. if (this._emissiveTexture === texture) {
  42537. return true;
  42538. }
  42539. if (this._specularTexture === texture) {
  42540. return true;
  42541. }
  42542. if (this._bumpTexture === texture) {
  42543. return true;
  42544. }
  42545. if (this._lightmapTexture === texture) {
  42546. return true;
  42547. }
  42548. if (this._refractionTexture === texture) {
  42549. return true;
  42550. }
  42551. return false;
  42552. };
  42553. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42554. if (forceDisposeTextures) {
  42555. if (this._diffuseTexture) {
  42556. this._diffuseTexture.dispose();
  42557. }
  42558. if (this._ambientTexture) {
  42559. this._ambientTexture.dispose();
  42560. }
  42561. if (this._opacityTexture) {
  42562. this._opacityTexture.dispose();
  42563. }
  42564. if (this._reflectionTexture) {
  42565. this._reflectionTexture.dispose();
  42566. }
  42567. if (this._emissiveTexture) {
  42568. this._emissiveTexture.dispose();
  42569. }
  42570. if (this._specularTexture) {
  42571. this._specularTexture.dispose();
  42572. }
  42573. if (this._bumpTexture) {
  42574. this._bumpTexture.dispose();
  42575. }
  42576. if (this._lightmapTexture) {
  42577. this._lightmapTexture.dispose();
  42578. }
  42579. if (this._refractionTexture) {
  42580. this._refractionTexture.dispose();
  42581. }
  42582. }
  42583. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42584. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42585. }
  42586. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42587. };
  42588. StandardMaterial.prototype.clone = function (name) {
  42589. var _this = this;
  42590. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42591. result.name = name;
  42592. result.id = name;
  42593. return result;
  42594. };
  42595. StandardMaterial.prototype.serialize = function () {
  42596. return BABYLON.SerializationHelper.Serialize(this);
  42597. };
  42598. // Statics
  42599. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42600. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42601. };
  42602. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42603. get: function () {
  42604. return StandardMaterial._DiffuseTextureEnabled;
  42605. },
  42606. set: function (value) {
  42607. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42608. return;
  42609. }
  42610. StandardMaterial._DiffuseTextureEnabled = value;
  42611. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42612. },
  42613. enumerable: true,
  42614. configurable: true
  42615. });
  42616. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42617. get: function () {
  42618. return StandardMaterial._AmbientTextureEnabled;
  42619. },
  42620. set: function (value) {
  42621. if (StandardMaterial._AmbientTextureEnabled === value) {
  42622. return;
  42623. }
  42624. StandardMaterial._AmbientTextureEnabled = value;
  42625. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42626. },
  42627. enumerable: true,
  42628. configurable: true
  42629. });
  42630. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42631. get: function () {
  42632. return StandardMaterial._OpacityTextureEnabled;
  42633. },
  42634. set: function (value) {
  42635. if (StandardMaterial._OpacityTextureEnabled === value) {
  42636. return;
  42637. }
  42638. StandardMaterial._OpacityTextureEnabled = value;
  42639. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42640. },
  42641. enumerable: true,
  42642. configurable: true
  42643. });
  42644. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42645. get: function () {
  42646. return StandardMaterial._ReflectionTextureEnabled;
  42647. },
  42648. set: function (value) {
  42649. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42650. return;
  42651. }
  42652. StandardMaterial._ReflectionTextureEnabled = value;
  42653. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42654. },
  42655. enumerable: true,
  42656. configurable: true
  42657. });
  42658. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42659. get: function () {
  42660. return StandardMaterial._EmissiveTextureEnabled;
  42661. },
  42662. set: function (value) {
  42663. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42664. return;
  42665. }
  42666. StandardMaterial._EmissiveTextureEnabled = value;
  42667. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42668. },
  42669. enumerable: true,
  42670. configurable: true
  42671. });
  42672. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42673. get: function () {
  42674. return StandardMaterial._SpecularTextureEnabled;
  42675. },
  42676. set: function (value) {
  42677. if (StandardMaterial._SpecularTextureEnabled === value) {
  42678. return;
  42679. }
  42680. StandardMaterial._SpecularTextureEnabled = value;
  42681. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42682. },
  42683. enumerable: true,
  42684. configurable: true
  42685. });
  42686. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42687. get: function () {
  42688. return StandardMaterial._BumpTextureEnabled;
  42689. },
  42690. set: function (value) {
  42691. if (StandardMaterial._BumpTextureEnabled === value) {
  42692. return;
  42693. }
  42694. StandardMaterial._BumpTextureEnabled = value;
  42695. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42696. },
  42697. enumerable: true,
  42698. configurable: true
  42699. });
  42700. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42701. get: function () {
  42702. return StandardMaterial._LightmapTextureEnabled;
  42703. },
  42704. set: function (value) {
  42705. if (StandardMaterial._LightmapTextureEnabled === value) {
  42706. return;
  42707. }
  42708. StandardMaterial._LightmapTextureEnabled = value;
  42709. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42710. },
  42711. enumerable: true,
  42712. configurable: true
  42713. });
  42714. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  42715. get: function () {
  42716. return StandardMaterial._RefractionTextureEnabled;
  42717. },
  42718. set: function (value) {
  42719. if (StandardMaterial._RefractionTextureEnabled === value) {
  42720. return;
  42721. }
  42722. StandardMaterial._RefractionTextureEnabled = value;
  42723. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42724. },
  42725. enumerable: true,
  42726. configurable: true
  42727. });
  42728. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  42729. get: function () {
  42730. return StandardMaterial._ColorGradingTextureEnabled;
  42731. },
  42732. set: function (value) {
  42733. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  42734. return;
  42735. }
  42736. StandardMaterial._ColorGradingTextureEnabled = value;
  42737. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42738. },
  42739. enumerable: true,
  42740. configurable: true
  42741. });
  42742. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  42743. get: function () {
  42744. return StandardMaterial._FresnelEnabled;
  42745. },
  42746. set: function (value) {
  42747. if (StandardMaterial._FresnelEnabled === value) {
  42748. return;
  42749. }
  42750. StandardMaterial._FresnelEnabled = value;
  42751. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  42752. },
  42753. enumerable: true,
  42754. configurable: true
  42755. });
  42756. // Flags used to enable or disable a type of texture for all Standard Materials
  42757. StandardMaterial._DiffuseTextureEnabled = true;
  42758. StandardMaterial._AmbientTextureEnabled = true;
  42759. StandardMaterial._OpacityTextureEnabled = true;
  42760. StandardMaterial._ReflectionTextureEnabled = true;
  42761. StandardMaterial._EmissiveTextureEnabled = true;
  42762. StandardMaterial._SpecularTextureEnabled = true;
  42763. StandardMaterial._BumpTextureEnabled = true;
  42764. StandardMaterial._LightmapTextureEnabled = true;
  42765. StandardMaterial._RefractionTextureEnabled = true;
  42766. StandardMaterial._ColorGradingTextureEnabled = true;
  42767. StandardMaterial._FresnelEnabled = true;
  42768. __decorate([
  42769. BABYLON.serializeAsTexture("diffuseTexture")
  42770. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  42771. __decorate([
  42772. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42773. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  42774. __decorate([
  42775. BABYLON.serializeAsTexture("ambientTexture")
  42776. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  42777. __decorate([
  42778. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42779. ], StandardMaterial.prototype, "ambientTexture", void 0);
  42780. __decorate([
  42781. BABYLON.serializeAsTexture("opacityTexture")
  42782. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  42783. __decorate([
  42784. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42785. ], StandardMaterial.prototype, "opacityTexture", void 0);
  42786. __decorate([
  42787. BABYLON.serializeAsTexture("reflectionTexture")
  42788. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  42789. __decorate([
  42790. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42791. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  42792. __decorate([
  42793. BABYLON.serializeAsTexture("emissiveTexture")
  42794. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  42795. __decorate([
  42796. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42797. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  42798. __decorate([
  42799. BABYLON.serializeAsTexture("specularTexture")
  42800. ], StandardMaterial.prototype, "_specularTexture", void 0);
  42801. __decorate([
  42802. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42803. ], StandardMaterial.prototype, "specularTexture", void 0);
  42804. __decorate([
  42805. BABYLON.serializeAsTexture("bumpTexture")
  42806. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  42807. __decorate([
  42808. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42809. ], StandardMaterial.prototype, "bumpTexture", void 0);
  42810. __decorate([
  42811. BABYLON.serializeAsTexture("lightmapTexture")
  42812. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  42813. __decorate([
  42814. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42815. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  42816. __decorate([
  42817. BABYLON.serializeAsTexture("refractionTexture")
  42818. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  42819. __decorate([
  42820. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42821. ], StandardMaterial.prototype, "refractionTexture", void 0);
  42822. __decorate([
  42823. BABYLON.serializeAsColor3("ambient")
  42824. ], StandardMaterial.prototype, "ambientColor", void 0);
  42825. __decorate([
  42826. BABYLON.serializeAsColor3("diffuse")
  42827. ], StandardMaterial.prototype, "diffuseColor", void 0);
  42828. __decorate([
  42829. BABYLON.serializeAsColor3("specular")
  42830. ], StandardMaterial.prototype, "specularColor", void 0);
  42831. __decorate([
  42832. BABYLON.serializeAsColor3("emissive")
  42833. ], StandardMaterial.prototype, "emissiveColor", void 0);
  42834. __decorate([
  42835. BABYLON.serialize()
  42836. ], StandardMaterial.prototype, "specularPower", void 0);
  42837. __decorate([
  42838. BABYLON.serialize("useAlphaFromDiffuseTexture")
  42839. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  42840. __decorate([
  42841. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42842. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  42843. __decorate([
  42844. BABYLON.serialize("useEmissiveAsIllumination")
  42845. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  42846. __decorate([
  42847. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42848. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  42849. __decorate([
  42850. BABYLON.serialize("linkEmissiveWithDiffuse")
  42851. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  42852. __decorate([
  42853. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42854. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  42855. __decorate([
  42856. BABYLON.serialize("useSpecularOverAlpha")
  42857. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  42858. __decorate([
  42859. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42860. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  42861. __decorate([
  42862. BABYLON.serialize("useReflectionOverAlpha")
  42863. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  42864. __decorate([
  42865. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42866. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  42867. __decorate([
  42868. BABYLON.serialize("disableLighting")
  42869. ], StandardMaterial.prototype, "_disableLighting", void 0);
  42870. __decorate([
  42871. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42872. ], StandardMaterial.prototype, "disableLighting", void 0);
  42873. __decorate([
  42874. BABYLON.serialize("useObjectSpaceNormalMap")
  42875. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  42876. __decorate([
  42877. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42878. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42879. __decorate([
  42880. BABYLON.serialize("useParallax")
  42881. ], StandardMaterial.prototype, "_useParallax", void 0);
  42882. __decorate([
  42883. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42884. ], StandardMaterial.prototype, "useParallax", void 0);
  42885. __decorate([
  42886. BABYLON.serialize("useParallaxOcclusion")
  42887. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  42888. __decorate([
  42889. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42890. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  42891. __decorate([
  42892. BABYLON.serialize()
  42893. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  42894. __decorate([
  42895. BABYLON.serialize("roughness")
  42896. ], StandardMaterial.prototype, "_roughness", void 0);
  42897. __decorate([
  42898. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42899. ], StandardMaterial.prototype, "roughness", void 0);
  42900. __decorate([
  42901. BABYLON.serialize()
  42902. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  42903. __decorate([
  42904. BABYLON.serialize()
  42905. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  42906. __decorate([
  42907. BABYLON.serialize("useLightmapAsShadowmap")
  42908. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  42909. __decorate([
  42910. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42911. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42912. __decorate([
  42913. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  42914. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  42915. __decorate([
  42916. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42917. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  42918. __decorate([
  42919. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  42920. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  42921. __decorate([
  42922. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  42923. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  42924. __decorate([
  42925. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  42926. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  42927. __decorate([
  42928. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42929. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  42930. __decorate([
  42931. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  42932. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  42933. __decorate([
  42934. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42935. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  42936. __decorate([
  42937. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  42938. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  42939. __decorate([
  42940. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42941. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  42942. __decorate([
  42943. BABYLON.serialize("useReflectionFresnelFromSpecular")
  42944. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  42945. __decorate([
  42946. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42947. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  42948. __decorate([
  42949. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  42950. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  42951. __decorate([
  42952. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42953. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  42954. __decorate([
  42955. BABYLON.serialize("maxSimultaneousLights")
  42956. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  42957. __decorate([
  42958. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42959. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  42960. __decorate([
  42961. BABYLON.serialize("invertNormalMapX")
  42962. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  42963. __decorate([
  42964. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42965. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  42966. __decorate([
  42967. BABYLON.serialize("invertNormalMapY")
  42968. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  42969. __decorate([
  42970. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42971. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  42972. __decorate([
  42973. BABYLON.serialize("twoSidedLighting")
  42974. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  42975. __decorate([
  42976. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42977. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  42978. __decorate([
  42979. BABYLON.serialize()
  42980. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  42981. return StandardMaterial;
  42982. }(BABYLON.PushMaterial));
  42983. BABYLON.StandardMaterial = StandardMaterial;
  42984. })(BABYLON || (BABYLON = {}));
  42985. //# sourceMappingURL=babylon.standardMaterial.js.map
  42986. "use strict";
  42987. var BABYLON;
  42988. (function (BABYLON) {
  42989. /**
  42990. * Manages the defines for the PBR Material.
  42991. * @ignoreChildren
  42992. */
  42993. var PBRMaterialDefines = /** @class */ (function (_super) {
  42994. __extends(PBRMaterialDefines, _super);
  42995. /**
  42996. * Initializes the PBR Material defines.
  42997. */
  42998. function PBRMaterialDefines() {
  42999. var _this = _super.call(this) || this;
  43000. _this.PBR = true;
  43001. _this.MAINUV1 = false;
  43002. _this.MAINUV2 = false;
  43003. _this.UV1 = false;
  43004. _this.UV2 = false;
  43005. _this.ALBEDO = false;
  43006. _this.ALBEDODIRECTUV = 0;
  43007. _this.VERTEXCOLOR = false;
  43008. _this.AMBIENT = false;
  43009. _this.AMBIENTDIRECTUV = 0;
  43010. _this.AMBIENTINGRAYSCALE = false;
  43011. _this.OPACITY = false;
  43012. _this.VERTEXALPHA = false;
  43013. _this.OPACITYDIRECTUV = 0;
  43014. _this.OPACITYRGB = false;
  43015. _this.ALPHATEST = false;
  43016. _this.DEPTHPREPASS = false;
  43017. _this.ALPHABLEND = false;
  43018. _this.ALPHAFROMALBEDO = false;
  43019. _this.ALPHATESTVALUE = "0.5";
  43020. _this.SPECULAROVERALPHA = false;
  43021. _this.RADIANCEOVERALPHA = false;
  43022. _this.ALPHAFRESNEL = false;
  43023. _this.LINEARALPHAFRESNEL = false;
  43024. _this.PREMULTIPLYALPHA = false;
  43025. _this.EMISSIVE = false;
  43026. _this.EMISSIVEDIRECTUV = 0;
  43027. _this.REFLECTIVITY = false;
  43028. _this.REFLECTIVITYDIRECTUV = 0;
  43029. _this.SPECULARTERM = false;
  43030. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43031. _this.MICROSURFACEAUTOMATIC = false;
  43032. _this.LODBASEDMICROSFURACE = false;
  43033. _this.MICROSURFACEMAP = false;
  43034. _this.MICROSURFACEMAPDIRECTUV = 0;
  43035. _this.METALLICWORKFLOW = false;
  43036. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43037. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43038. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43039. _this.AOSTOREINMETALMAPRED = false;
  43040. _this.ENVIRONMENTBRDF = false;
  43041. _this.NORMAL = false;
  43042. _this.TANGENT = false;
  43043. _this.BUMP = false;
  43044. _this.BUMPDIRECTUV = 0;
  43045. _this.OBJECTSPACE_NORMALMAP = false;
  43046. _this.PARALLAX = false;
  43047. _this.PARALLAXOCCLUSION = false;
  43048. _this.NORMALXYSCALE = true;
  43049. _this.LIGHTMAP = false;
  43050. _this.LIGHTMAPDIRECTUV = 0;
  43051. _this.USELIGHTMAPASSHADOWMAP = false;
  43052. _this.GAMMALIGHTMAP = false;
  43053. _this.REFLECTION = false;
  43054. _this.REFLECTIONMAP_3D = false;
  43055. _this.REFLECTIONMAP_SPHERICAL = false;
  43056. _this.REFLECTIONMAP_PLANAR = false;
  43057. _this.REFLECTIONMAP_CUBIC = false;
  43058. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43059. _this.REFLECTIONMAP_PROJECTION = false;
  43060. _this.REFLECTIONMAP_SKYBOX = false;
  43061. _this.REFLECTIONMAP_EXPLICIT = false;
  43062. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43063. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43064. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43065. _this.INVERTCUBICMAP = false;
  43066. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43067. _this.USESPHERICALINVERTEX = false;
  43068. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43069. _this.LODINREFLECTIONALPHA = false;
  43070. _this.GAMMAREFLECTION = false;
  43071. _this.RADIANCEOCCLUSION = false;
  43072. _this.HORIZONOCCLUSION = false;
  43073. _this.REFRACTION = false;
  43074. _this.REFRACTIONMAP_3D = false;
  43075. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43076. _this.LODINREFRACTIONALPHA = false;
  43077. _this.GAMMAREFRACTION = false;
  43078. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43079. _this.INSTANCES = false;
  43080. _this.NUM_BONE_INFLUENCERS = 0;
  43081. _this.BonesPerMesh = 0;
  43082. _this.NONUNIFORMSCALING = false;
  43083. _this.MORPHTARGETS = false;
  43084. _this.MORPHTARGETS_NORMAL = false;
  43085. _this.MORPHTARGETS_TANGENT = false;
  43086. _this.NUM_MORPH_INFLUENCERS = 0;
  43087. _this.IMAGEPROCESSING = false;
  43088. _this.VIGNETTE = false;
  43089. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43090. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43091. _this.TONEMAPPING = false;
  43092. _this.CONTRAST = false;
  43093. _this.COLORCURVES = false;
  43094. _this.COLORGRADING = false;
  43095. _this.COLORGRADING3D = false;
  43096. _this.SAMPLER3DGREENDEPTH = false;
  43097. _this.SAMPLER3DBGRMAP = false;
  43098. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43099. _this.EXPOSURE = false;
  43100. _this.USEPHYSICALLIGHTFALLOFF = false;
  43101. _this.TWOSIDEDLIGHTING = false;
  43102. _this.SHADOWFLOAT = false;
  43103. _this.CLIPPLANE = false;
  43104. _this.POINTSIZE = false;
  43105. _this.FOG = false;
  43106. _this.LOGARITHMICDEPTH = false;
  43107. _this.FORCENORMALFORWARD = false;
  43108. _this.GEOMETRYAA = false;
  43109. _this.UNLIT = false;
  43110. _this.rebuild();
  43111. return _this;
  43112. }
  43113. /**
  43114. * Resets the PBR Material defines.
  43115. */
  43116. PBRMaterialDefines.prototype.reset = function () {
  43117. _super.prototype.reset.call(this);
  43118. this.ALPHATESTVALUE = "0.5";
  43119. this.PBR = true;
  43120. };
  43121. return PBRMaterialDefines;
  43122. }(BABYLON.MaterialDefines));
  43123. /**
  43124. * The Physically based material base class of BJS.
  43125. *
  43126. * This offers the main features of a standard PBR material.
  43127. * For more information, please refer to the documentation :
  43128. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43129. */
  43130. var PBRBaseMaterial = /** @class */ (function (_super) {
  43131. __extends(PBRBaseMaterial, _super);
  43132. /**
  43133. * Instantiates a new PBRMaterial instance.
  43134. *
  43135. * @param name The material name
  43136. * @param scene The scene the material will be use in.
  43137. */
  43138. function PBRBaseMaterial(name, scene) {
  43139. var _this = _super.call(this, name, scene) || this;
  43140. /**
  43141. * Intensity of the direct lights e.g. the four lights available in your scene.
  43142. * This impacts both the direct diffuse and specular highlights.
  43143. */
  43144. _this._directIntensity = 1.0;
  43145. /**
  43146. * Intensity of the emissive part of the material.
  43147. * This helps controlling the emissive effect without modifying the emissive color.
  43148. */
  43149. _this._emissiveIntensity = 1.0;
  43150. /**
  43151. * Intensity of the environment e.g. how much the environment will light the object
  43152. * either through harmonics for rough material or through the refelction for shiny ones.
  43153. */
  43154. _this._environmentIntensity = 1.0;
  43155. /**
  43156. * This is a special control allowing the reduction of the specular highlights coming from the
  43157. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43158. */
  43159. _this._specularIntensity = 1.0;
  43160. /**
  43161. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43162. */
  43163. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43164. /**
  43165. * Debug Control allowing disabling the bump map on this material.
  43166. */
  43167. _this._disableBumpMap = false;
  43168. /**
  43169. * AKA Occlusion Texture Intensity in other nomenclature.
  43170. */
  43171. _this._ambientTextureStrength = 1.0;
  43172. /**
  43173. * The color of a material in ambient lighting.
  43174. */
  43175. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43176. /**
  43177. * AKA Diffuse Color in other nomenclature.
  43178. */
  43179. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43180. /**
  43181. * AKA Specular Color in other nomenclature.
  43182. */
  43183. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43184. /**
  43185. * The color applied when light is reflected from a material.
  43186. */
  43187. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43188. /**
  43189. * The color applied when light is emitted from a material.
  43190. */
  43191. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43192. /**
  43193. * AKA Glossiness in other nomenclature.
  43194. */
  43195. _this._microSurface = 0.9;
  43196. /**
  43197. * source material index of refraction (IOR)' / 'destination material IOR.
  43198. */
  43199. _this._indexOfRefraction = 0.66;
  43200. /**
  43201. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43202. */
  43203. _this._invertRefractionY = false;
  43204. /**
  43205. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43206. * Materials half opaque for instance using refraction could benefit from this control.
  43207. */
  43208. _this._linkRefractionWithTransparency = false;
  43209. /**
  43210. * Specifies that the material will use the light map as a show map.
  43211. */
  43212. _this._useLightmapAsShadowmap = false;
  43213. /**
  43214. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43215. * makes the reflect vector face the model (under horizon).
  43216. */
  43217. _this._useHorizonOcclusion = true;
  43218. /**
  43219. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43220. * too much the area relying on ambient texture to define their ambient occlusion.
  43221. */
  43222. _this._useRadianceOcclusion = true;
  43223. /**
  43224. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43225. */
  43226. _this._useAlphaFromAlbedoTexture = false;
  43227. /**
  43228. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43229. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43230. */
  43231. _this._useSpecularOverAlpha = true;
  43232. /**
  43233. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43234. */
  43235. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43236. /**
  43237. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43238. */
  43239. _this._useRoughnessFromMetallicTextureAlpha = true;
  43240. /**
  43241. * Specifies if the metallic texture contains the roughness information in its green channel.
  43242. */
  43243. _this._useRoughnessFromMetallicTextureGreen = false;
  43244. /**
  43245. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43246. */
  43247. _this._useMetallnessFromMetallicTextureBlue = false;
  43248. /**
  43249. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43250. */
  43251. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43252. /**
  43253. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43254. */
  43255. _this._useAmbientInGrayScale = false;
  43256. /**
  43257. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43258. * The material will try to infer what glossiness each pixel should be.
  43259. */
  43260. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43261. /**
  43262. * BJS is using an harcoded light falloff based on a manually sets up range.
  43263. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  43264. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  43265. */
  43266. _this._usePhysicalLightFalloff = true;
  43267. /**
  43268. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43269. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43270. */
  43271. _this._useRadianceOverAlpha = true;
  43272. /**
  43273. * Allows using an object space normal map (instead of tangent space).
  43274. */
  43275. _this._useObjectSpaceNormalMap = false;
  43276. /**
  43277. * Allows using the bump map in parallax mode.
  43278. */
  43279. _this._useParallax = false;
  43280. /**
  43281. * Allows using the bump map in parallax occlusion mode.
  43282. */
  43283. _this._useParallaxOcclusion = false;
  43284. /**
  43285. * Controls the scale bias of the parallax mode.
  43286. */
  43287. _this._parallaxScaleBias = 0.05;
  43288. /**
  43289. * If sets to true, disables all the lights affecting the material.
  43290. */
  43291. _this._disableLighting = false;
  43292. /**
  43293. * Number of Simultaneous lights allowed on the material.
  43294. */
  43295. _this._maxSimultaneousLights = 4;
  43296. /**
  43297. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43298. */
  43299. _this._invertNormalMapX = false;
  43300. /**
  43301. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43302. */
  43303. _this._invertNormalMapY = false;
  43304. /**
  43305. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43306. */
  43307. _this._twoSidedLighting = false;
  43308. /**
  43309. * Defines the alpha limits in alpha test mode.
  43310. */
  43311. _this._alphaCutOff = 0.4;
  43312. /**
  43313. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43314. */
  43315. _this._forceAlphaTest = false;
  43316. /**
  43317. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43318. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43319. */
  43320. _this._useAlphaFresnel = false;
  43321. /**
  43322. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43323. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43324. */
  43325. _this._useLinearAlphaFresnel = false;
  43326. /**
  43327. * The transparency mode of the material.
  43328. */
  43329. _this._transparencyMode = null;
  43330. /**
  43331. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43332. * from cos thetav and roughness:
  43333. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43334. */
  43335. _this._environmentBRDFTexture = null;
  43336. /**
  43337. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43338. */
  43339. _this._forceIrradianceInFragment = false;
  43340. /**
  43341. * Force normal to face away from face.
  43342. */
  43343. _this._forceNormalForward = false;
  43344. /**
  43345. * Enables specular anti aliasing in the PBR shader.
  43346. * It will both interacts on the Geometry for analytical and IBL lighting.
  43347. * It also prefilter the roughness map based on the bump values.
  43348. */
  43349. _this._enableSpecularAntiAliasing = false;
  43350. /**
  43351. * Stores the available render targets.
  43352. */
  43353. _this._renderTargets = new BABYLON.SmartArray(16);
  43354. /**
  43355. * Sets the global ambient color for the material used in lighting calculations.
  43356. */
  43357. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43358. /**
  43359. * If set to true, no lighting calculations will be applied.
  43360. */
  43361. _this._unlit = false;
  43362. // Setup the default processing configuration to the scene.
  43363. _this._attachImageProcessingConfiguration(null);
  43364. _this.getRenderTargetTextures = function () {
  43365. _this._renderTargets.reset();
  43366. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43367. _this._renderTargets.push(_this._reflectionTexture);
  43368. }
  43369. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43370. _this._renderTargets.push(_this._refractionTexture);
  43371. }
  43372. return _this._renderTargets;
  43373. };
  43374. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43375. return _this;
  43376. }
  43377. /**
  43378. * Attaches a new image processing configuration to the PBR Material.
  43379. * @param configuration
  43380. */
  43381. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43382. var _this = this;
  43383. if (configuration === this._imageProcessingConfiguration) {
  43384. return;
  43385. }
  43386. // Detaches observer.
  43387. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43388. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43389. }
  43390. // Pick the scene configuration if needed.
  43391. if (!configuration) {
  43392. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43393. }
  43394. else {
  43395. this._imageProcessingConfiguration = configuration;
  43396. }
  43397. // Attaches observer.
  43398. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43399. _this._markAllSubMeshesAsImageProcessingDirty();
  43400. });
  43401. };
  43402. /**
  43403. * Gets the name of the material class.
  43404. */
  43405. PBRBaseMaterial.prototype.getClassName = function () {
  43406. return "PBRBaseMaterial";
  43407. };
  43408. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43409. /**
  43410. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43411. */
  43412. get: function () {
  43413. return this._useLogarithmicDepth;
  43414. },
  43415. /**
  43416. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43417. */
  43418. set: function (value) {
  43419. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43420. },
  43421. enumerable: true,
  43422. configurable: true
  43423. });
  43424. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43425. /**
  43426. * Gets the current transparency mode.
  43427. */
  43428. get: function () {
  43429. return this._transparencyMode;
  43430. },
  43431. /**
  43432. * Sets the transparency mode of the material.
  43433. */
  43434. set: function (value) {
  43435. if (this._transparencyMode === value) {
  43436. return;
  43437. }
  43438. this._transparencyMode = value;
  43439. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43440. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43441. },
  43442. enumerable: true,
  43443. configurable: true
  43444. });
  43445. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43446. /**
  43447. * Returns true if alpha blending should be disabled.
  43448. */
  43449. get: function () {
  43450. return (this._linkRefractionWithTransparency ||
  43451. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43452. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43453. },
  43454. enumerable: true,
  43455. configurable: true
  43456. });
  43457. /**
  43458. * Specifies whether or not this material should be rendered in alpha blend mode.
  43459. */
  43460. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43461. if (this._disableAlphaBlending) {
  43462. return false;
  43463. }
  43464. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43465. };
  43466. /**
  43467. * Specifies if the mesh will require alpha blending.
  43468. * @param mesh - BJS mesh.
  43469. */
  43470. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43471. if (this._disableAlphaBlending) {
  43472. return false;
  43473. }
  43474. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43475. };
  43476. /**
  43477. * Specifies whether or not this material should be rendered in alpha test mode.
  43478. */
  43479. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43480. if (this._forceAlphaTest) {
  43481. return true;
  43482. }
  43483. if (this._linkRefractionWithTransparency) {
  43484. return false;
  43485. }
  43486. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43487. };
  43488. /**
  43489. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  43490. */
  43491. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  43492. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  43493. };
  43494. /**
  43495. * Gets the texture used for the alpha test.
  43496. */
  43497. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  43498. return this._albedoTexture;
  43499. };
  43500. /**
  43501. * Specifies that the submesh is ready to be used.
  43502. * @param mesh - BJS mesh.
  43503. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  43504. * @param useInstances - Specifies that instances should be used.
  43505. * @returns - boolean indicating that the submesh is ready or not.
  43506. */
  43507. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43508. if (subMesh.effect && this.isFrozen) {
  43509. if (this._wasPreviouslyReady) {
  43510. return true;
  43511. }
  43512. }
  43513. if (!subMesh._materialDefines) {
  43514. subMesh._materialDefines = new PBRMaterialDefines();
  43515. }
  43516. var defines = subMesh._materialDefines;
  43517. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43518. if (defines._renderId === this.getScene().getRenderId()) {
  43519. return true;
  43520. }
  43521. }
  43522. var scene = this.getScene();
  43523. var engine = scene.getEngine();
  43524. if (defines._areTexturesDirty) {
  43525. if (scene.texturesEnabled) {
  43526. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43527. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  43528. return false;
  43529. }
  43530. }
  43531. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43532. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43533. return false;
  43534. }
  43535. }
  43536. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43537. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43538. return false;
  43539. }
  43540. }
  43541. var reflectionTexture = this._getReflectionTexture();
  43542. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43543. if (!reflectionTexture.isReadyOrNotBlocking()) {
  43544. return false;
  43545. }
  43546. }
  43547. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43548. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43549. return false;
  43550. }
  43551. }
  43552. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43553. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43554. return false;
  43555. }
  43556. }
  43557. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43558. if (this._metallicTexture) {
  43559. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  43560. return false;
  43561. }
  43562. }
  43563. else if (this._reflectivityTexture) {
  43564. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  43565. return false;
  43566. }
  43567. }
  43568. if (this._microSurfaceTexture) {
  43569. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  43570. return false;
  43571. }
  43572. }
  43573. }
  43574. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43575. // Bump texture cannot be not blocking.
  43576. if (!this._bumpTexture.isReady()) {
  43577. return false;
  43578. }
  43579. }
  43580. var refractionTexture = this._getRefractionTexture();
  43581. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43582. if (!refractionTexture.isReadyOrNotBlocking()) {
  43583. return false;
  43584. }
  43585. }
  43586. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43587. // This is blocking.
  43588. if (!this._environmentBRDFTexture.isReady()) {
  43589. return false;
  43590. }
  43591. }
  43592. }
  43593. }
  43594. if (defines._areImageProcessingDirty) {
  43595. if (!this._imageProcessingConfiguration.isReady()) {
  43596. return false;
  43597. }
  43598. }
  43599. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  43600. mesh.createNormals(true);
  43601. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  43602. }
  43603. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  43604. if (effect) {
  43605. scene.resetCachedMaterial();
  43606. subMesh.setEffect(effect, defines);
  43607. this.buildUniformLayout();
  43608. }
  43609. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43610. return false;
  43611. }
  43612. defines._renderId = scene.getRenderId();
  43613. this._wasPreviouslyReady = true;
  43614. return true;
  43615. };
  43616. /**
  43617. * Specifies if the material uses metallic roughness workflow.
  43618. * @returns boolean specifiying if the material uses metallic roughness workflow.
  43619. */
  43620. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  43621. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  43622. return true;
  43623. }
  43624. return false;
  43625. };
  43626. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  43627. if (onCompiled === void 0) { onCompiled = null; }
  43628. if (onError === void 0) { onError = null; }
  43629. if (useInstances === void 0) { useInstances = null; }
  43630. if (useClipPlane === void 0) { useClipPlane = null; }
  43631. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  43632. if (!defines.isDirty) {
  43633. return null;
  43634. }
  43635. defines.markAsProcessed();
  43636. var scene = this.getScene();
  43637. var engine = scene.getEngine();
  43638. // Fallbacks
  43639. var fallbacks = new BABYLON.EffectFallbacks();
  43640. var fallbackRank = 0;
  43641. if (defines.USESPHERICALINVERTEX) {
  43642. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  43643. }
  43644. if (defines.FOG) {
  43645. fallbacks.addFallback(fallbackRank, "FOG");
  43646. }
  43647. if (defines.POINTSIZE) {
  43648. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  43649. }
  43650. if (defines.LOGARITHMICDEPTH) {
  43651. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  43652. }
  43653. if (defines.PARALLAX) {
  43654. fallbacks.addFallback(fallbackRank, "PARALLAX");
  43655. }
  43656. if (defines.PARALLAXOCCLUSION) {
  43657. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  43658. }
  43659. if (defines.ENVIRONMENTBRDF) {
  43660. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  43661. }
  43662. if (defines.TANGENT) {
  43663. fallbacks.addFallback(fallbackRank++, "TANGENT");
  43664. }
  43665. if (defines.BUMP) {
  43666. fallbacks.addFallback(fallbackRank++, "BUMP");
  43667. }
  43668. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  43669. if (defines.SPECULARTERM) {
  43670. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  43671. }
  43672. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  43673. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  43674. }
  43675. if (defines.LIGHTMAP) {
  43676. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  43677. }
  43678. if (defines.NORMAL) {
  43679. fallbacks.addFallback(fallbackRank++, "NORMAL");
  43680. }
  43681. if (defines.AMBIENT) {
  43682. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  43683. }
  43684. if (defines.EMISSIVE) {
  43685. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  43686. }
  43687. if (defines.VERTEXCOLOR) {
  43688. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  43689. }
  43690. if (defines.NUM_BONE_INFLUENCERS > 0) {
  43691. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  43692. }
  43693. if (defines.MORPHTARGETS) {
  43694. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  43695. }
  43696. //Attributes
  43697. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43698. if (defines.NORMAL) {
  43699. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43700. }
  43701. if (defines.TANGENT) {
  43702. attribs.push(BABYLON.VertexBuffer.TangentKind);
  43703. }
  43704. if (defines.UV1) {
  43705. attribs.push(BABYLON.VertexBuffer.UVKind);
  43706. }
  43707. if (defines.UV2) {
  43708. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43709. }
  43710. if (defines.VERTEXCOLOR) {
  43711. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43712. }
  43713. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43714. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43715. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43716. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  43717. "vFogInfos", "vFogColor", "pointSize",
  43718. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  43719. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43720. "mBones",
  43721. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  43722. "vLightingIntensity",
  43723. "logarithmicDepthConstant",
  43724. "vSphericalX", "vSphericalY", "vSphericalZ",
  43725. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  43726. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  43727. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  43728. "vTangentSpaceParams"
  43729. ];
  43730. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  43731. "bumpSampler", "lightmapSampler", "opacitySampler",
  43732. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  43733. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  43734. "microSurfaceSampler", "environmentBrdfSampler"];
  43735. var uniformBuffers = ["Material", "Scene"];
  43736. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43737. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43738. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43739. uniformsNames: uniforms,
  43740. uniformBuffersNames: uniformBuffers,
  43741. samplers: samplers,
  43742. defines: defines,
  43743. maxSimultaneousLights: this._maxSimultaneousLights
  43744. });
  43745. var join = defines.toString();
  43746. return engine.createEffect("pbr", {
  43747. attributes: attribs,
  43748. uniformsNames: uniforms,
  43749. uniformBuffersNames: uniformBuffers,
  43750. samplers: samplers,
  43751. defines: join,
  43752. fallbacks: fallbacks,
  43753. onCompiled: onCompiled,
  43754. onError: onError,
  43755. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43756. }, engine);
  43757. };
  43758. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  43759. if (useInstances === void 0) { useInstances = null; }
  43760. if (useClipPlane === void 0) { useClipPlane = null; }
  43761. var scene = this.getScene();
  43762. var engine = scene.getEngine();
  43763. // Lights
  43764. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43765. defines._needNormals = true;
  43766. // Textures
  43767. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  43768. if (defines._areTexturesDirty) {
  43769. defines._needUVs = false;
  43770. if (scene.texturesEnabled) {
  43771. if (scene.getEngine().getCaps().textureLOD) {
  43772. defines.LODBASEDMICROSFURACE = true;
  43773. }
  43774. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43775. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  43776. }
  43777. else {
  43778. defines.ALBEDO = false;
  43779. }
  43780. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43781. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43782. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  43783. }
  43784. else {
  43785. defines.AMBIENT = false;
  43786. }
  43787. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43788. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43789. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43790. }
  43791. else {
  43792. defines.OPACITY = false;
  43793. }
  43794. var reflectionTexture = this._getReflectionTexture();
  43795. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43796. defines.REFLECTION = true;
  43797. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  43798. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  43799. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  43800. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  43801. defines.INVERTCUBICMAP = true;
  43802. }
  43803. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  43804. switch (reflectionTexture.coordinatesMode) {
  43805. case BABYLON.Texture.CUBIC_MODE:
  43806. case BABYLON.Texture.INVCUBIC_MODE:
  43807. defines.REFLECTIONMAP_CUBIC = true;
  43808. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  43809. break;
  43810. case BABYLON.Texture.EXPLICIT_MODE:
  43811. defines.REFLECTIONMAP_EXPLICIT = true;
  43812. break;
  43813. case BABYLON.Texture.PLANAR_MODE:
  43814. defines.REFLECTIONMAP_PLANAR = true;
  43815. break;
  43816. case BABYLON.Texture.PROJECTION_MODE:
  43817. defines.REFLECTIONMAP_PROJECTION = true;
  43818. break;
  43819. case BABYLON.Texture.SKYBOX_MODE:
  43820. defines.REFLECTIONMAP_SKYBOX = true;
  43821. break;
  43822. case BABYLON.Texture.SPHERICAL_MODE:
  43823. defines.REFLECTIONMAP_SPHERICAL = true;
  43824. break;
  43825. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43826. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  43827. break;
  43828. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43829. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  43830. break;
  43831. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43832. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  43833. break;
  43834. }
  43835. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  43836. if (reflectionTexture.sphericalPolynomial) {
  43837. defines.USESPHERICALFROMREFLECTIONMAP = true;
  43838. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  43839. defines.USESPHERICALINVERTEX = false;
  43840. }
  43841. else {
  43842. defines.USESPHERICALINVERTEX = true;
  43843. }
  43844. }
  43845. }
  43846. }
  43847. else {
  43848. defines.REFLECTION = false;
  43849. defines.REFLECTIONMAP_3D = false;
  43850. defines.REFLECTIONMAP_SPHERICAL = false;
  43851. defines.REFLECTIONMAP_PLANAR = false;
  43852. defines.REFLECTIONMAP_CUBIC = false;
  43853. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43854. defines.REFLECTIONMAP_PROJECTION = false;
  43855. defines.REFLECTIONMAP_SKYBOX = false;
  43856. defines.REFLECTIONMAP_EXPLICIT = false;
  43857. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43858. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43859. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43860. defines.INVERTCUBICMAP = false;
  43861. defines.USESPHERICALFROMREFLECTIONMAP = false;
  43862. defines.USESPHERICALINVERTEX = false;
  43863. defines.REFLECTIONMAP_OPPOSITEZ = false;
  43864. defines.LODINREFLECTIONALPHA = false;
  43865. defines.GAMMAREFLECTION = false;
  43866. }
  43867. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43868. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43869. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43870. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  43871. }
  43872. else {
  43873. defines.LIGHTMAP = false;
  43874. }
  43875. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43876. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43877. }
  43878. else {
  43879. defines.EMISSIVE = false;
  43880. }
  43881. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43882. if (this._metallicTexture) {
  43883. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  43884. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  43885. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  43886. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  43887. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  43888. }
  43889. else if (this._reflectivityTexture) {
  43890. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  43891. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  43892. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  43893. }
  43894. else {
  43895. defines.REFLECTIVITY = false;
  43896. }
  43897. if (this._microSurfaceTexture) {
  43898. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  43899. }
  43900. else {
  43901. defines.MICROSURFACEMAP = false;
  43902. }
  43903. }
  43904. else {
  43905. defines.REFLECTIVITY = false;
  43906. defines.MICROSURFACEMAP = false;
  43907. }
  43908. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43909. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43910. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43911. defines.PARALLAX = true;
  43912. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  43913. }
  43914. else {
  43915. defines.PARALLAX = false;
  43916. }
  43917. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43918. }
  43919. else {
  43920. defines.BUMP = false;
  43921. }
  43922. var refractionTexture = this._getRefractionTexture();
  43923. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43924. defines.REFRACTION = true;
  43925. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  43926. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  43927. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  43928. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  43929. if (this._linkRefractionWithTransparency) {
  43930. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  43931. }
  43932. }
  43933. else {
  43934. defines.REFRACTION = false;
  43935. }
  43936. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43937. defines.ENVIRONMENTBRDF = true;
  43938. }
  43939. else {
  43940. defines.ENVIRONMENTBRDF = false;
  43941. }
  43942. if (this._shouldUseAlphaFromAlbedoTexture()) {
  43943. defines.ALPHAFROMALBEDO = true;
  43944. }
  43945. else {
  43946. defines.ALPHAFROMALBEDO = false;
  43947. }
  43948. }
  43949. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43950. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  43951. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  43952. if (!this.backFaceCulling && this._twoSidedLighting) {
  43953. defines.TWOSIDEDLIGHTING = true;
  43954. }
  43955. else {
  43956. defines.TWOSIDEDLIGHTING = false;
  43957. }
  43958. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  43959. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  43960. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  43961. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  43962. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  43963. defines.GEOMETRYAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  43964. }
  43965. if (defines._areImageProcessingDirty) {
  43966. this._imageProcessingConfiguration.prepareDefines(defines);
  43967. }
  43968. defines.FORCENORMALFORWARD = this._forceNormalForward;
  43969. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  43970. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  43971. // Misc.
  43972. if (defines._areMiscDirty) {
  43973. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  43974. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  43975. }
  43976. // Values that need to be evaluated on every frame
  43977. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  43978. // Attribs
  43979. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  43980. };
  43981. /**
  43982. * Force shader compilation
  43983. */
  43984. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  43985. var _this = this;
  43986. var localOptions = __assign({ clipPlane: false }, options);
  43987. var defines = new PBRMaterialDefines();
  43988. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  43989. if (effect.isReady()) {
  43990. if (onCompiled) {
  43991. onCompiled(this);
  43992. }
  43993. }
  43994. else {
  43995. effect.onCompileObservable.add(function () {
  43996. if (onCompiled) {
  43997. onCompiled(_this);
  43998. }
  43999. });
  44000. }
  44001. };
  44002. /**
  44003. * Initializes the uniform buffer layout for the shader.
  44004. */
  44005. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44006. // Order is important !
  44007. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44008. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  44009. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44010. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44011. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44012. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44013. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44014. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44015. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44016. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44017. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44018. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44019. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44020. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44021. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44022. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44023. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44024. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44025. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44026. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44027. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44028. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44029. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44030. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44031. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44032. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44033. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44034. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44035. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44036. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44037. this._uniformBuffer.addUniform("pointSize", 1);
  44038. this._uniformBuffer.create();
  44039. };
  44040. /**
  44041. * Unbinds the textures.
  44042. */
  44043. PBRBaseMaterial.prototype.unbind = function () {
  44044. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44045. this._uniformBuffer.setTexture("reflectionSampler", null);
  44046. }
  44047. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44048. this._uniformBuffer.setTexture("refractionSampler", null);
  44049. }
  44050. _super.prototype.unbind.call(this);
  44051. };
  44052. /**
  44053. * Binds the submesh data.
  44054. * @param world - The world matrix.
  44055. * @param mesh - The BJS mesh.
  44056. * @param subMesh - A submesh of the BJS mesh.
  44057. */
  44058. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44059. var scene = this.getScene();
  44060. var defines = subMesh._materialDefines;
  44061. if (!defines) {
  44062. return;
  44063. }
  44064. var effect = subMesh.effect;
  44065. if (!effect) {
  44066. return;
  44067. }
  44068. this._activeEffect = effect;
  44069. // Matrices
  44070. this.bindOnlyWorldMatrix(world);
  44071. // Normal Matrix
  44072. if (defines.OBJECTSPACE_NORMALMAP) {
  44073. world.toNormalMatrix(this._normalMatrix);
  44074. this.bindOnlyNormalMatrix(this._normalMatrix);
  44075. }
  44076. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44077. // Bones
  44078. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44079. var reflectionTexture = null;
  44080. if (mustRebind) {
  44081. this._uniformBuffer.bindToEffect(effect, "Material");
  44082. this.bindViewProjection(effect);
  44083. reflectionTexture = this._getReflectionTexture();
  44084. var refractionTexture = this._getRefractionTexture();
  44085. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44086. // Texture uniforms
  44087. if (scene.texturesEnabled) {
  44088. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44089. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44090. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44091. }
  44092. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44093. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  44094. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44095. }
  44096. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44097. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44098. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44099. }
  44100. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44101. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44102. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44103. if (reflectionTexture.boundingBoxSize) {
  44104. var cubeTexture = reflectionTexture;
  44105. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44106. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44107. }
  44108. var polynomials = reflectionTexture.sphericalPolynomial;
  44109. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44110. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44111. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44112. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44113. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44114. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44115. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44116. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44117. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44118. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44119. }
  44120. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44121. }
  44122. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44123. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44124. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44125. }
  44126. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44127. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44128. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44129. }
  44130. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44131. if (this._metallicTexture) {
  44132. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44133. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44134. }
  44135. else if (this._reflectivityTexture) {
  44136. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44137. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44138. }
  44139. if (this._microSurfaceTexture) {
  44140. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44141. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44142. }
  44143. }
  44144. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44145. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44146. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44147. if (scene._mirroredCameraPosition) {
  44148. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44149. }
  44150. else {
  44151. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44152. }
  44153. }
  44154. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44155. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44156. var depth = 1.0;
  44157. if (!refractionTexture.isCube) {
  44158. if (refractionTexture.depth) {
  44159. depth = refractionTexture.depth;
  44160. }
  44161. }
  44162. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44163. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44164. }
  44165. }
  44166. // Point size
  44167. if (this.pointsCloud) {
  44168. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44169. }
  44170. // Colors
  44171. if (defines.METALLICWORKFLOW) {
  44172. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44173. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44174. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44175. }
  44176. else {
  44177. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44178. }
  44179. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44180. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44181. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44182. // Misc
  44183. this._lightingInfos.x = this._directIntensity;
  44184. this._lightingInfos.y = this._emissiveIntensity;
  44185. this._lightingInfos.z = this._environmentIntensity;
  44186. this._lightingInfos.w = this._specularIntensity;
  44187. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44188. }
  44189. // Textures
  44190. if (scene.texturesEnabled) {
  44191. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44192. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44193. }
  44194. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44195. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44196. }
  44197. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44198. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44199. }
  44200. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44201. if (defines.LODBASEDMICROSFURACE) {
  44202. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44203. }
  44204. else {
  44205. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44206. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44207. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44208. }
  44209. }
  44210. if (defines.ENVIRONMENTBRDF) {
  44211. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44212. }
  44213. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44214. if (defines.LODBASEDMICROSFURACE) {
  44215. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44216. }
  44217. else {
  44218. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44219. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44220. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44221. }
  44222. }
  44223. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44224. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44225. }
  44226. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44227. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44228. }
  44229. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44230. if (this._metallicTexture) {
  44231. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44232. }
  44233. else if (this._reflectivityTexture) {
  44234. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44235. }
  44236. if (this._microSurfaceTexture) {
  44237. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44238. }
  44239. }
  44240. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44241. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44242. }
  44243. }
  44244. // Clip plane
  44245. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44246. // Colors
  44247. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44248. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44249. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44250. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44251. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44252. }
  44253. if (mustRebind || !this.isFrozen) {
  44254. // Lights
  44255. if (scene.lightsEnabled && !this._disableLighting) {
  44256. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  44257. }
  44258. // View
  44259. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44260. this.bindView(effect);
  44261. }
  44262. // Fog
  44263. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44264. // Morph targets
  44265. if (defines.NUM_MORPH_INFLUENCERS) {
  44266. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44267. }
  44268. // image processing
  44269. this._imageProcessingConfiguration.bind(this._activeEffect);
  44270. // Log. depth
  44271. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44272. }
  44273. this._uniformBuffer.update();
  44274. this._afterBind(mesh);
  44275. };
  44276. /**
  44277. * Returns the animatable textures.
  44278. * @returns - Array of animatable textures.
  44279. */
  44280. PBRBaseMaterial.prototype.getAnimatables = function () {
  44281. var results = [];
  44282. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44283. results.push(this._albedoTexture);
  44284. }
  44285. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44286. results.push(this._ambientTexture);
  44287. }
  44288. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44289. results.push(this._opacityTexture);
  44290. }
  44291. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44292. results.push(this._reflectionTexture);
  44293. }
  44294. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44295. results.push(this._emissiveTexture);
  44296. }
  44297. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44298. results.push(this._metallicTexture);
  44299. }
  44300. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44301. results.push(this._reflectivityTexture);
  44302. }
  44303. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44304. results.push(this._bumpTexture);
  44305. }
  44306. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44307. results.push(this._lightmapTexture);
  44308. }
  44309. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44310. results.push(this._refractionTexture);
  44311. }
  44312. return results;
  44313. };
  44314. /**
  44315. * Returns the texture used for reflections.
  44316. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44317. */
  44318. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44319. if (this._reflectionTexture) {
  44320. return this._reflectionTexture;
  44321. }
  44322. return this.getScene().environmentTexture;
  44323. };
  44324. /**
  44325. * Returns the texture used for refraction or null if none is used.
  44326. * @returns - Refection texture if present. If no refraction texture and refraction
  44327. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44328. */
  44329. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44330. if (this._refractionTexture) {
  44331. return this._refractionTexture;
  44332. }
  44333. if (this._linkRefractionWithTransparency) {
  44334. return this.getScene().environmentTexture;
  44335. }
  44336. return null;
  44337. };
  44338. /**
  44339. * Disposes the resources of the material.
  44340. * @param forceDisposeEffect - Forces the disposal of effects.
  44341. * @param forceDisposeTextures - Forces the disposal of all textures.
  44342. */
  44343. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44344. if (forceDisposeTextures) {
  44345. if (this._albedoTexture) {
  44346. this._albedoTexture.dispose();
  44347. }
  44348. if (this._ambientTexture) {
  44349. this._ambientTexture.dispose();
  44350. }
  44351. if (this._opacityTexture) {
  44352. this._opacityTexture.dispose();
  44353. }
  44354. if (this._reflectionTexture) {
  44355. this._reflectionTexture.dispose();
  44356. }
  44357. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44358. this._environmentBRDFTexture.dispose();
  44359. }
  44360. if (this._emissiveTexture) {
  44361. this._emissiveTexture.dispose();
  44362. }
  44363. if (this._metallicTexture) {
  44364. this._metallicTexture.dispose();
  44365. }
  44366. if (this._reflectivityTexture) {
  44367. this._reflectivityTexture.dispose();
  44368. }
  44369. if (this._bumpTexture) {
  44370. this._bumpTexture.dispose();
  44371. }
  44372. if (this._lightmapTexture) {
  44373. this._lightmapTexture.dispose();
  44374. }
  44375. if (this._refractionTexture) {
  44376. this._refractionTexture.dispose();
  44377. }
  44378. }
  44379. this._renderTargets.dispose();
  44380. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44381. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44382. }
  44383. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44384. };
  44385. /**
  44386. * Stores the reflectivity values based on metallic roughness workflow.
  44387. */
  44388. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44389. __decorate([
  44390. BABYLON.serializeAsImageProcessingConfiguration()
  44391. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44392. __decorate([
  44393. BABYLON.serialize()
  44394. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44395. __decorate([
  44396. BABYLON.serialize()
  44397. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44398. return PBRBaseMaterial;
  44399. }(BABYLON.PushMaterial));
  44400. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44401. })(BABYLON || (BABYLON = {}));
  44402. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44403. "use strict";
  44404. var BABYLON;
  44405. (function (BABYLON) {
  44406. /**
  44407. * The Physically based simple base material of BJS.
  44408. *
  44409. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44410. * It is used as the base class for both the specGloss and metalRough conventions.
  44411. */
  44412. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44413. __extends(PBRBaseSimpleMaterial, _super);
  44414. /**
  44415. * Instantiates a new PBRMaterial instance.
  44416. *
  44417. * @param name The material name
  44418. * @param scene The scene the material will be use in.
  44419. */
  44420. function PBRBaseSimpleMaterial(name, scene) {
  44421. var _this = _super.call(this, name, scene) || this;
  44422. /**
  44423. * Number of Simultaneous lights allowed on the material.
  44424. */
  44425. _this.maxSimultaneousLights = 4;
  44426. /**
  44427. * If sets to true, disables all the lights affecting the material.
  44428. */
  44429. _this.disableLighting = false;
  44430. /**
  44431. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44432. */
  44433. _this.invertNormalMapX = false;
  44434. /**
  44435. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44436. */
  44437. _this.invertNormalMapY = false;
  44438. /**
  44439. * Emissivie color used to self-illuminate the model.
  44440. */
  44441. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44442. /**
  44443. * Occlusion Channel Strenght.
  44444. */
  44445. _this.occlusionStrength = 1.0;
  44446. _this.useLightmapAsShadowmap = false;
  44447. _this._useAlphaFromAlbedoTexture = true;
  44448. _this._useAmbientInGrayScale = true;
  44449. return _this;
  44450. }
  44451. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44452. /**
  44453. * Gets the current double sided mode.
  44454. */
  44455. get: function () {
  44456. return this._twoSidedLighting;
  44457. },
  44458. /**
  44459. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44460. */
  44461. set: function (value) {
  44462. if (this._twoSidedLighting === value) {
  44463. return;
  44464. }
  44465. this._twoSidedLighting = value;
  44466. this.backFaceCulling = !value;
  44467. this._markAllSubMeshesAsTexturesDirty();
  44468. },
  44469. enumerable: true,
  44470. configurable: true
  44471. });
  44472. /**
  44473. * Return the active textures of the material.
  44474. */
  44475. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  44476. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44477. if (this.environmentTexture) {
  44478. activeTextures.push(this.environmentTexture);
  44479. }
  44480. if (this.normalTexture) {
  44481. activeTextures.push(this.normalTexture);
  44482. }
  44483. if (this.emissiveTexture) {
  44484. activeTextures.push(this.emissiveTexture);
  44485. }
  44486. if (this.occlusionTexture) {
  44487. activeTextures.push(this.occlusionTexture);
  44488. }
  44489. if (this.lightmapTexture) {
  44490. activeTextures.push(this.lightmapTexture);
  44491. }
  44492. return activeTextures;
  44493. };
  44494. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  44495. if (_super.prototype.hasTexture.call(this, texture)) {
  44496. return true;
  44497. }
  44498. if (this.lightmapTexture === texture) {
  44499. return true;
  44500. }
  44501. return false;
  44502. };
  44503. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  44504. return "PBRBaseSimpleMaterial";
  44505. };
  44506. __decorate([
  44507. BABYLON.serialize(),
  44508. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44509. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  44510. __decorate([
  44511. BABYLON.serialize(),
  44512. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44513. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  44514. __decorate([
  44515. BABYLON.serializeAsTexture(),
  44516. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  44517. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  44518. __decorate([
  44519. BABYLON.serialize(),
  44520. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44521. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  44522. __decorate([
  44523. BABYLON.serialize(),
  44524. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44525. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  44526. __decorate([
  44527. BABYLON.serializeAsTexture(),
  44528. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  44529. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  44530. __decorate([
  44531. BABYLON.serializeAsColor3("emissive"),
  44532. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44533. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  44534. __decorate([
  44535. BABYLON.serializeAsTexture(),
  44536. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44537. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  44538. __decorate([
  44539. BABYLON.serialize(),
  44540. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  44541. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  44542. __decorate([
  44543. BABYLON.serializeAsTexture(),
  44544. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  44545. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  44546. __decorate([
  44547. BABYLON.serialize(),
  44548. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  44549. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  44550. __decorate([
  44551. BABYLON.serialize()
  44552. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  44553. __decorate([
  44554. BABYLON.serializeAsTexture(),
  44555. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  44556. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  44557. __decorate([
  44558. BABYLON.serialize(),
  44559. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44560. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44561. return PBRBaseSimpleMaterial;
  44562. }(BABYLON.PBRBaseMaterial));
  44563. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  44564. })(BABYLON || (BABYLON = {}));
  44565. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  44566. "use strict";
  44567. var BABYLON;
  44568. (function (BABYLON) {
  44569. /**
  44570. * The Physically based material of BJS.
  44571. *
  44572. * This offers the main features of a standard PBR material.
  44573. * For more information, please refer to the documentation :
  44574. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44575. */
  44576. var PBRMaterial = /** @class */ (function (_super) {
  44577. __extends(PBRMaterial, _super);
  44578. /**
  44579. * Instantiates a new PBRMaterial instance.
  44580. *
  44581. * @param name The material name
  44582. * @param scene The scene the material will be use in.
  44583. */
  44584. function PBRMaterial(name, scene) {
  44585. var _this = _super.call(this, name, scene) || this;
  44586. /**
  44587. * Intensity of the direct lights e.g. the four lights available in your scene.
  44588. * This impacts both the direct diffuse and specular highlights.
  44589. */
  44590. _this.directIntensity = 1.0;
  44591. /**
  44592. * Intensity of the emissive part of the material.
  44593. * This helps controlling the emissive effect without modifying the emissive color.
  44594. */
  44595. _this.emissiveIntensity = 1.0;
  44596. /**
  44597. * Intensity of the environment e.g. how much the environment will light the object
  44598. * either through harmonics for rough material or through the refelction for shiny ones.
  44599. */
  44600. _this.environmentIntensity = 1.0;
  44601. /**
  44602. * This is a special control allowing the reduction of the specular highlights coming from the
  44603. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44604. */
  44605. _this.specularIntensity = 1.0;
  44606. /**
  44607. * Debug Control allowing disabling the bump map on this material.
  44608. */
  44609. _this.disableBumpMap = false;
  44610. /**
  44611. * AKA Occlusion Texture Intensity in other nomenclature.
  44612. */
  44613. _this.ambientTextureStrength = 1.0;
  44614. /**
  44615. * The color of a material in ambient lighting.
  44616. */
  44617. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  44618. /**
  44619. * AKA Diffuse Color in other nomenclature.
  44620. */
  44621. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  44622. /**
  44623. * AKA Specular Color in other nomenclature.
  44624. */
  44625. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44626. /**
  44627. * The color reflected from the material.
  44628. */
  44629. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  44630. /**
  44631. * The color emitted from the material.
  44632. */
  44633. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44634. /**
  44635. * AKA Glossiness in other nomenclature.
  44636. */
  44637. _this.microSurface = 1.0;
  44638. /**
  44639. * source material index of refraction (IOR)' / 'destination material IOR.
  44640. */
  44641. _this.indexOfRefraction = 0.66;
  44642. /**
  44643. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44644. */
  44645. _this.invertRefractionY = false;
  44646. /**
  44647. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44648. * Materials half opaque for instance using refraction could benefit from this control.
  44649. */
  44650. _this.linkRefractionWithTransparency = false;
  44651. _this.useLightmapAsShadowmap = false;
  44652. /**
  44653. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44654. */
  44655. _this.useAlphaFromAlbedoTexture = false;
  44656. /**
  44657. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44658. */
  44659. _this.forceAlphaTest = false;
  44660. /**
  44661. * Defines the alpha limits in alpha test mode.
  44662. */
  44663. _this.alphaCutOff = 0.4;
  44664. /**
  44665. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44666. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44667. */
  44668. _this.useSpecularOverAlpha = true;
  44669. /**
  44670. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44671. */
  44672. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  44673. /**
  44674. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44675. */
  44676. _this.useRoughnessFromMetallicTextureAlpha = true;
  44677. /**
  44678. * Specifies if the metallic texture contains the roughness information in its green channel.
  44679. */
  44680. _this.useRoughnessFromMetallicTextureGreen = false;
  44681. /**
  44682. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44683. */
  44684. _this.useMetallnessFromMetallicTextureBlue = false;
  44685. /**
  44686. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44687. */
  44688. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  44689. /**
  44690. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44691. */
  44692. _this.useAmbientInGrayScale = false;
  44693. /**
  44694. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44695. * The material will try to infer what glossiness each pixel should be.
  44696. */
  44697. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  44698. /**
  44699. * BJS is using an harcoded light falloff based on a manually sets up range.
  44700. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44701. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44702. */
  44703. _this.usePhysicalLightFalloff = true;
  44704. /**
  44705. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44706. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44707. */
  44708. _this.useRadianceOverAlpha = true;
  44709. /**
  44710. * Allows using an object space normal map (instead of tangent space).
  44711. */
  44712. _this.useObjectSpaceNormalMap = false;
  44713. /**
  44714. * Allows using the bump map in parallax mode.
  44715. */
  44716. _this.useParallax = false;
  44717. /**
  44718. * Allows using the bump map in parallax occlusion mode.
  44719. */
  44720. _this.useParallaxOcclusion = false;
  44721. /**
  44722. * Controls the scale bias of the parallax mode.
  44723. */
  44724. _this.parallaxScaleBias = 0.05;
  44725. /**
  44726. * If sets to true, disables all the lights affecting the material.
  44727. */
  44728. _this.disableLighting = false;
  44729. /**
  44730. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44731. */
  44732. _this.forceIrradianceInFragment = false;
  44733. /**
  44734. * Number of Simultaneous lights allowed on the material.
  44735. */
  44736. _this.maxSimultaneousLights = 4;
  44737. /**
  44738. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44739. */
  44740. _this.invertNormalMapX = false;
  44741. /**
  44742. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44743. */
  44744. _this.invertNormalMapY = false;
  44745. /**
  44746. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44747. */
  44748. _this.twoSidedLighting = false;
  44749. /**
  44750. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44751. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44752. */
  44753. _this.useAlphaFresnel = false;
  44754. /**
  44755. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44756. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44757. */
  44758. _this.useLinearAlphaFresnel = false;
  44759. /**
  44760. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44761. * And/Or occlude the blended part.
  44762. */
  44763. _this.environmentBRDFTexture = null;
  44764. /**
  44765. * Force normal to face away from face.
  44766. */
  44767. _this.forceNormalForward = false;
  44768. /**
  44769. * Enables specular anti aliasing in the PBR shader.
  44770. * It will both interacts on the Geometry for analytical and IBL lighting.
  44771. * It also prefilter the roughness map based on the bump values.
  44772. */
  44773. _this.enableSpecularAntiAliasing = false;
  44774. /**
  44775. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44776. * makes the reflect vector face the model (under horizon).
  44777. */
  44778. _this.useHorizonOcclusion = true;
  44779. /**
  44780. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44781. * too much the area relying on ambient texture to define their ambient occlusion.
  44782. */
  44783. _this.useRadianceOcclusion = true;
  44784. /**
  44785. * If set to true, no lighting calculations will be applied.
  44786. */
  44787. _this.unlit = false;
  44788. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44789. return _this;
  44790. }
  44791. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  44792. /**
  44793. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  44794. */
  44795. get: function () {
  44796. return this._PBRMATERIAL_OPAQUE;
  44797. },
  44798. enumerable: true,
  44799. configurable: true
  44800. });
  44801. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  44802. /**
  44803. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  44804. */
  44805. get: function () {
  44806. return this._PBRMATERIAL_ALPHATEST;
  44807. },
  44808. enumerable: true,
  44809. configurable: true
  44810. });
  44811. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  44812. /**
  44813. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  44814. */
  44815. get: function () {
  44816. return this._PBRMATERIAL_ALPHABLEND;
  44817. },
  44818. enumerable: true,
  44819. configurable: true
  44820. });
  44821. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  44822. /**
  44823. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  44824. * They are also discarded below the alpha cutoff threshold to improve performances.
  44825. */
  44826. get: function () {
  44827. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  44828. },
  44829. enumerable: true,
  44830. configurable: true
  44831. });
  44832. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  44833. /**
  44834. * Gets the image processing configuration used either in this material.
  44835. */
  44836. get: function () {
  44837. return this._imageProcessingConfiguration;
  44838. },
  44839. /**
  44840. * Sets the Default image processing configuration used either in the this material.
  44841. *
  44842. * If sets to null, the scene one is in use.
  44843. */
  44844. set: function (value) {
  44845. this._attachImageProcessingConfiguration(value);
  44846. // Ensure the effect will be rebuilt.
  44847. this._markAllSubMeshesAsTexturesDirty();
  44848. },
  44849. enumerable: true,
  44850. configurable: true
  44851. });
  44852. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  44853. /**
  44854. * Gets wether the color curves effect is enabled.
  44855. */
  44856. get: function () {
  44857. return this.imageProcessingConfiguration.colorCurvesEnabled;
  44858. },
  44859. /**
  44860. * Sets wether the color curves effect is enabled.
  44861. */
  44862. set: function (value) {
  44863. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  44864. },
  44865. enumerable: true,
  44866. configurable: true
  44867. });
  44868. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  44869. /**
  44870. * Gets wether the color grading effect is enabled.
  44871. */
  44872. get: function () {
  44873. return this.imageProcessingConfiguration.colorGradingEnabled;
  44874. },
  44875. /**
  44876. * Gets wether the color grading effect is enabled.
  44877. */
  44878. set: function (value) {
  44879. this.imageProcessingConfiguration.colorGradingEnabled = value;
  44880. },
  44881. enumerable: true,
  44882. configurable: true
  44883. });
  44884. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  44885. /**
  44886. * Gets wether tonemapping is enabled or not.
  44887. */
  44888. get: function () {
  44889. return this._imageProcessingConfiguration.toneMappingEnabled;
  44890. },
  44891. /**
  44892. * Sets wether tonemapping is enabled or not
  44893. */
  44894. set: function (value) {
  44895. this._imageProcessingConfiguration.toneMappingEnabled = value;
  44896. },
  44897. enumerable: true,
  44898. configurable: true
  44899. });
  44900. ;
  44901. ;
  44902. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  44903. /**
  44904. * The camera exposure used on this material.
  44905. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  44906. * This corresponds to a photographic exposure.
  44907. */
  44908. get: function () {
  44909. return this._imageProcessingConfiguration.exposure;
  44910. },
  44911. /**
  44912. * The camera exposure used on this material.
  44913. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  44914. * This corresponds to a photographic exposure.
  44915. */
  44916. set: function (value) {
  44917. this._imageProcessingConfiguration.exposure = value;
  44918. },
  44919. enumerable: true,
  44920. configurable: true
  44921. });
  44922. ;
  44923. ;
  44924. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  44925. /**
  44926. * Gets The camera contrast used on this material.
  44927. */
  44928. get: function () {
  44929. return this._imageProcessingConfiguration.contrast;
  44930. },
  44931. /**
  44932. * Sets The camera contrast used on this material.
  44933. */
  44934. set: function (value) {
  44935. this._imageProcessingConfiguration.contrast = value;
  44936. },
  44937. enumerable: true,
  44938. configurable: true
  44939. });
  44940. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  44941. /**
  44942. * Gets the Color Grading 2D Lookup Texture.
  44943. */
  44944. get: function () {
  44945. return this._imageProcessingConfiguration.colorGradingTexture;
  44946. },
  44947. /**
  44948. * Sets the Color Grading 2D Lookup Texture.
  44949. */
  44950. set: function (value) {
  44951. this._imageProcessingConfiguration.colorGradingTexture = value;
  44952. },
  44953. enumerable: true,
  44954. configurable: true
  44955. });
  44956. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  44957. /**
  44958. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  44959. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  44960. * 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;
  44961. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  44962. */
  44963. get: function () {
  44964. return this._imageProcessingConfiguration.colorCurves;
  44965. },
  44966. /**
  44967. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  44968. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  44969. * 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;
  44970. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  44971. */
  44972. set: function (value) {
  44973. this._imageProcessingConfiguration.colorCurves = value;
  44974. },
  44975. enumerable: true,
  44976. configurable: true
  44977. });
  44978. /**
  44979. * Returns the name of this material class.
  44980. */
  44981. PBRMaterial.prototype.getClassName = function () {
  44982. return "PBRMaterial";
  44983. };
  44984. /**
  44985. * Returns an array of the actively used textures.
  44986. * @returns - Array of BaseTextures
  44987. */
  44988. PBRMaterial.prototype.getActiveTextures = function () {
  44989. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44990. if (this._albedoTexture) {
  44991. activeTextures.push(this._albedoTexture);
  44992. }
  44993. if (this._ambientTexture) {
  44994. activeTextures.push(this._ambientTexture);
  44995. }
  44996. if (this._opacityTexture) {
  44997. activeTextures.push(this._opacityTexture);
  44998. }
  44999. if (this._reflectionTexture) {
  45000. activeTextures.push(this._reflectionTexture);
  45001. }
  45002. if (this._emissiveTexture) {
  45003. activeTextures.push(this._emissiveTexture);
  45004. }
  45005. if (this._reflectivityTexture) {
  45006. activeTextures.push(this._reflectivityTexture);
  45007. }
  45008. if (this._metallicTexture) {
  45009. activeTextures.push(this._metallicTexture);
  45010. }
  45011. if (this._microSurfaceTexture) {
  45012. activeTextures.push(this._microSurfaceTexture);
  45013. }
  45014. if (this._bumpTexture) {
  45015. activeTextures.push(this._bumpTexture);
  45016. }
  45017. if (this._lightmapTexture) {
  45018. activeTextures.push(this._lightmapTexture);
  45019. }
  45020. if (this._refractionTexture) {
  45021. activeTextures.push(this._refractionTexture);
  45022. }
  45023. return activeTextures;
  45024. };
  45025. /**
  45026. * Checks to see if a texture is used in the material.
  45027. * @param texture - Base texture to use.
  45028. * @returns - Boolean specifying if a texture is used in the material.
  45029. */
  45030. PBRMaterial.prototype.hasTexture = function (texture) {
  45031. if (_super.prototype.hasTexture.call(this, texture)) {
  45032. return true;
  45033. }
  45034. if (this._albedoTexture === texture) {
  45035. return true;
  45036. }
  45037. if (this._ambientTexture === texture) {
  45038. return true;
  45039. }
  45040. if (this._opacityTexture === texture) {
  45041. return true;
  45042. }
  45043. if (this._reflectionTexture === texture) {
  45044. return true;
  45045. }
  45046. if (this._reflectivityTexture === texture) {
  45047. return true;
  45048. }
  45049. if (this._metallicTexture === texture) {
  45050. return true;
  45051. }
  45052. if (this._microSurfaceTexture === texture) {
  45053. return true;
  45054. }
  45055. if (this._bumpTexture === texture) {
  45056. return true;
  45057. }
  45058. if (this._lightmapTexture === texture) {
  45059. return true;
  45060. }
  45061. if (this._refractionTexture === texture) {
  45062. return true;
  45063. }
  45064. return false;
  45065. };
  45066. /**
  45067. * Makes a duplicate of the current material.
  45068. * @param name - name to use for the new material.
  45069. */
  45070. PBRMaterial.prototype.clone = function (name) {
  45071. var _this = this;
  45072. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45073. clone.id = name;
  45074. clone.name = name;
  45075. return clone;
  45076. };
  45077. /**
  45078. * Serializes this PBR Material.
  45079. * @returns - An object with the serialized material.
  45080. */
  45081. PBRMaterial.prototype.serialize = function () {
  45082. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45083. serializationObject.customType = "BABYLON.PBRMaterial";
  45084. return serializationObject;
  45085. };
  45086. // Statics
  45087. /**
  45088. * Parses a PBR Material from a serialized object.
  45089. * @param source - Serialized object.
  45090. * @param scene - BJS scene instance.
  45091. * @param rootUrl - url for the scene object
  45092. * @returns - PBRMaterial
  45093. */
  45094. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45095. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45096. };
  45097. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  45098. /**
  45099. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45100. */
  45101. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  45102. /**
  45103. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45104. */
  45105. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  45106. /**
  45107. * 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.
  45108. * They are also discarded below the alpha cutoff threshold to improve performances.
  45109. */
  45110. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45111. __decorate([
  45112. BABYLON.serialize(),
  45113. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45114. ], PBRMaterial.prototype, "directIntensity", void 0);
  45115. __decorate([
  45116. BABYLON.serialize(),
  45117. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45118. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45119. __decorate([
  45120. BABYLON.serialize(),
  45121. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45122. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45123. __decorate([
  45124. BABYLON.serialize(),
  45125. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45126. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45127. __decorate([
  45128. BABYLON.serialize(),
  45129. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45130. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45131. __decorate([
  45132. BABYLON.serializeAsTexture(),
  45133. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45134. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45135. __decorate([
  45136. BABYLON.serializeAsTexture(),
  45137. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45138. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45139. __decorate([
  45140. BABYLON.serialize(),
  45141. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45142. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45143. __decorate([
  45144. BABYLON.serializeAsTexture(),
  45145. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45146. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45147. __decorate([
  45148. BABYLON.serializeAsTexture(),
  45149. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45150. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45151. __decorate([
  45152. BABYLON.serializeAsTexture(),
  45153. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45154. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45155. __decorate([
  45156. BABYLON.serializeAsTexture(),
  45157. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45158. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45159. __decorate([
  45160. BABYLON.serializeAsTexture(),
  45161. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45162. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45163. __decorate([
  45164. BABYLON.serialize(),
  45165. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45166. ], PBRMaterial.prototype, "metallic", void 0);
  45167. __decorate([
  45168. BABYLON.serialize(),
  45169. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45170. ], PBRMaterial.prototype, "roughness", void 0);
  45171. __decorate([
  45172. BABYLON.serializeAsTexture(),
  45173. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45174. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45175. __decorate([
  45176. BABYLON.serializeAsTexture(),
  45177. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45178. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45179. __decorate([
  45180. BABYLON.serializeAsTexture(),
  45181. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45182. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45183. __decorate([
  45184. BABYLON.serializeAsTexture(),
  45185. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45186. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45187. __decorate([
  45188. BABYLON.serializeAsColor3("ambient"),
  45189. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45190. ], PBRMaterial.prototype, "ambientColor", void 0);
  45191. __decorate([
  45192. BABYLON.serializeAsColor3("albedo"),
  45193. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45194. ], PBRMaterial.prototype, "albedoColor", void 0);
  45195. __decorate([
  45196. BABYLON.serializeAsColor3("reflectivity"),
  45197. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45198. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45199. __decorate([
  45200. BABYLON.serializeAsColor3("reflection"),
  45201. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45202. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45203. __decorate([
  45204. BABYLON.serializeAsColor3("emissive"),
  45205. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45206. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45207. __decorate([
  45208. BABYLON.serialize(),
  45209. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45210. ], PBRMaterial.prototype, "microSurface", void 0);
  45211. __decorate([
  45212. BABYLON.serialize(),
  45213. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45214. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45215. __decorate([
  45216. BABYLON.serialize(),
  45217. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45218. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45219. __decorate([
  45220. BABYLON.serialize(),
  45221. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45222. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45223. __decorate([
  45224. BABYLON.serialize(),
  45225. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45226. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45227. __decorate([
  45228. BABYLON.serialize(),
  45229. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45230. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45231. __decorate([
  45232. BABYLON.serialize(),
  45233. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45234. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45235. __decorate([
  45236. BABYLON.serialize(),
  45237. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45238. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45239. __decorate([
  45240. BABYLON.serialize(),
  45241. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45242. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45243. __decorate([
  45244. BABYLON.serialize(),
  45245. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45246. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45247. __decorate([
  45248. BABYLON.serialize(),
  45249. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45250. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45251. __decorate([
  45252. BABYLON.serialize(),
  45253. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45254. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45255. __decorate([
  45256. BABYLON.serialize(),
  45257. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45258. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45259. __decorate([
  45260. BABYLON.serialize(),
  45261. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45262. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45263. __decorate([
  45264. BABYLON.serialize(),
  45265. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45266. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45267. __decorate([
  45268. BABYLON.serialize(),
  45269. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45270. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45271. __decorate([
  45272. BABYLON.serialize(),
  45273. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45274. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  45275. __decorate([
  45276. BABYLON.serialize(),
  45277. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45278. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45279. __decorate([
  45280. BABYLON.serialize(),
  45281. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45282. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45283. __decorate([
  45284. BABYLON.serialize(),
  45285. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45286. ], PBRMaterial.prototype, "useParallax", void 0);
  45287. __decorate([
  45288. BABYLON.serialize(),
  45289. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45290. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45291. __decorate([
  45292. BABYLON.serialize(),
  45293. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45294. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45295. __decorate([
  45296. BABYLON.serialize(),
  45297. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45298. ], PBRMaterial.prototype, "disableLighting", void 0);
  45299. __decorate([
  45300. BABYLON.serialize(),
  45301. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45302. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45303. __decorate([
  45304. BABYLON.serialize(),
  45305. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45306. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45307. __decorate([
  45308. BABYLON.serialize(),
  45309. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45310. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45311. __decorate([
  45312. BABYLON.serialize(),
  45313. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45314. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45315. __decorate([
  45316. BABYLON.serialize(),
  45317. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45318. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45319. __decorate([
  45320. BABYLON.serialize(),
  45321. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45322. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45323. __decorate([
  45324. BABYLON.serialize(),
  45325. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45326. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45327. __decorate([
  45328. BABYLON.serializeAsTexture(),
  45329. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45330. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45331. __decorate([
  45332. BABYLON.serialize(),
  45333. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45334. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45335. __decorate([
  45336. BABYLON.serialize(),
  45337. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45338. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45339. __decorate([
  45340. BABYLON.serialize(),
  45341. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45342. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45343. __decorate([
  45344. BABYLON.serialize(),
  45345. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45346. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45347. __decorate([
  45348. BABYLON.serialize(),
  45349. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45350. ], PBRMaterial.prototype, "unlit", void 0);
  45351. return PBRMaterial;
  45352. }(BABYLON.PBRBaseMaterial));
  45353. BABYLON.PBRMaterial = PBRMaterial;
  45354. })(BABYLON || (BABYLON = {}));
  45355. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45356. "use strict";
  45357. var BABYLON;
  45358. (function (BABYLON) {
  45359. /**
  45360. * The PBR material of BJS following the metal roughness convention.
  45361. *
  45362. * This fits to the PBR convention in the GLTF definition:
  45363. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45364. */
  45365. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45366. __extends(PBRMetallicRoughnessMaterial, _super);
  45367. /**
  45368. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45369. *
  45370. * @param name The material name
  45371. * @param scene The scene the material will be use in.
  45372. */
  45373. function PBRMetallicRoughnessMaterial(name, scene) {
  45374. var _this = _super.call(this, name, scene) || this;
  45375. _this._useRoughnessFromMetallicTextureAlpha = false;
  45376. _this._useRoughnessFromMetallicTextureGreen = true;
  45377. _this._useMetallnessFromMetallicTextureBlue = true;
  45378. _this.metallic = 1.0;
  45379. _this.roughness = 1.0;
  45380. return _this;
  45381. }
  45382. /**
  45383. * Return the currrent class name of the material.
  45384. */
  45385. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45386. return "PBRMetallicRoughnessMaterial";
  45387. };
  45388. /**
  45389. * Return the active textures of the material.
  45390. */
  45391. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45392. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45393. if (this.baseTexture) {
  45394. activeTextures.push(this.baseTexture);
  45395. }
  45396. if (this.metallicRoughnessTexture) {
  45397. activeTextures.push(this.metallicRoughnessTexture);
  45398. }
  45399. return activeTextures;
  45400. };
  45401. /**
  45402. * Checks to see if a texture is used in the material.
  45403. * @param texture - Base texture to use.
  45404. * @returns - Boolean specifying if a texture is used in the material.
  45405. */
  45406. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45407. if (_super.prototype.hasTexture.call(this, texture)) {
  45408. return true;
  45409. }
  45410. if (this.baseTexture === texture) {
  45411. return true;
  45412. }
  45413. if (this.metallicRoughnessTexture === texture) {
  45414. return true;
  45415. }
  45416. return false;
  45417. };
  45418. /**
  45419. * Makes a duplicate of the current material.
  45420. * @param name - name to use for the new material.
  45421. */
  45422. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45423. var _this = this;
  45424. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45425. clone.id = name;
  45426. clone.name = name;
  45427. return clone;
  45428. };
  45429. /**
  45430. * Serialize the material to a parsable JSON object.
  45431. */
  45432. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45433. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45434. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45435. return serializationObject;
  45436. };
  45437. /**
  45438. * Parses a JSON object correponding to the serialize function.
  45439. */
  45440. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45441. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45442. };
  45443. __decorate([
  45444. BABYLON.serializeAsColor3(),
  45445. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45446. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45447. __decorate([
  45448. BABYLON.serializeAsTexture(),
  45449. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45450. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45451. __decorate([
  45452. BABYLON.serialize(),
  45453. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45454. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45455. __decorate([
  45456. BABYLON.serialize(),
  45457. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45458. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  45459. __decorate([
  45460. BABYLON.serializeAsTexture(),
  45461. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  45462. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  45463. return PBRMetallicRoughnessMaterial;
  45464. }(BABYLON.PBRBaseSimpleMaterial));
  45465. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  45466. })(BABYLON || (BABYLON = {}));
  45467. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  45468. "use strict";
  45469. var BABYLON;
  45470. (function (BABYLON) {
  45471. /**
  45472. * The PBR material of BJS following the specular glossiness convention.
  45473. *
  45474. * This fits to the PBR convention in the GLTF definition:
  45475. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  45476. */
  45477. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  45478. __extends(PBRSpecularGlossinessMaterial, _super);
  45479. /**
  45480. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  45481. *
  45482. * @param name The material name
  45483. * @param scene The scene the material will be use in.
  45484. */
  45485. function PBRSpecularGlossinessMaterial(name, scene) {
  45486. var _this = _super.call(this, name, scene) || this;
  45487. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  45488. return _this;
  45489. }
  45490. /**
  45491. * Return the currrent class name of the material.
  45492. */
  45493. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  45494. return "PBRSpecularGlossinessMaterial";
  45495. };
  45496. /**
  45497. * Return the active textures of the material.
  45498. */
  45499. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  45500. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45501. if (this.diffuseTexture) {
  45502. activeTextures.push(this.diffuseTexture);
  45503. }
  45504. if (this.specularGlossinessTexture) {
  45505. activeTextures.push(this.specularGlossinessTexture);
  45506. }
  45507. return activeTextures;
  45508. };
  45509. /**
  45510. * Checks to see if a texture is used in the material.
  45511. * @param texture - Base texture to use.
  45512. * @returns - Boolean specifying if a texture is used in the material.
  45513. */
  45514. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  45515. if (_super.prototype.hasTexture.call(this, texture)) {
  45516. return true;
  45517. }
  45518. if (this.diffuseTexture === texture) {
  45519. return true;
  45520. }
  45521. if (this.specularGlossinessTexture === texture) {
  45522. return true;
  45523. }
  45524. return false;
  45525. };
  45526. /**
  45527. * Makes a duplicate of the current material.
  45528. * @param name - name to use for the new material.
  45529. */
  45530. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  45531. var _this = this;
  45532. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  45533. clone.id = name;
  45534. clone.name = name;
  45535. return clone;
  45536. };
  45537. /**
  45538. * Serialize the material to a parsable JSON object.
  45539. */
  45540. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  45541. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45542. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  45543. return serializationObject;
  45544. };
  45545. /**
  45546. * Parses a JSON object correponding to the serialize function.
  45547. */
  45548. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  45549. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  45550. };
  45551. __decorate([
  45552. BABYLON.serializeAsColor3("diffuse"),
  45553. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45554. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  45555. __decorate([
  45556. BABYLON.serializeAsTexture(),
  45557. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45558. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  45559. __decorate([
  45560. BABYLON.serializeAsColor3("specular"),
  45561. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  45562. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  45563. __decorate([
  45564. BABYLON.serialize(),
  45565. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  45566. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  45567. __decorate([
  45568. BABYLON.serializeAsTexture(),
  45569. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  45570. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  45571. return PBRSpecularGlossinessMaterial;
  45572. }(BABYLON.PBRBaseSimpleMaterial));
  45573. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  45574. })(BABYLON || (BABYLON = {}));
  45575. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  45576. "use strict";
  45577. var BABYLON;
  45578. (function (BABYLON) {
  45579. BABYLON.CameraInputTypes = {};
  45580. var CameraInputsManager = /** @class */ (function () {
  45581. function CameraInputsManager(camera) {
  45582. this.attached = {};
  45583. this.camera = camera;
  45584. this.checkInputs = function () { };
  45585. }
  45586. /**
  45587. * Add an input method to a camera.
  45588. * builtin inputs example: camera.inputs.addGamepad();
  45589. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  45590. * @param input camera input method
  45591. */
  45592. CameraInputsManager.prototype.add = function (input) {
  45593. var type = input.getSimpleName();
  45594. if (this.attached[type]) {
  45595. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  45596. return;
  45597. }
  45598. this.attached[type] = input;
  45599. input.camera = this.camera;
  45600. //for checkInputs, we are dynamically creating a function
  45601. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  45602. if (input.checkInputs) {
  45603. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45604. }
  45605. if (this.attachedElement) {
  45606. input.attachControl(this.attachedElement);
  45607. }
  45608. };
  45609. /**
  45610. * Remove a specific input method from a camera
  45611. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  45612. * @param inputToRemove camera input method
  45613. */
  45614. CameraInputsManager.prototype.remove = function (inputToRemove) {
  45615. for (var cam in this.attached) {
  45616. var input = this.attached[cam];
  45617. if (input === inputToRemove) {
  45618. input.detachControl(this.attachedElement);
  45619. input.camera = null;
  45620. delete this.attached[cam];
  45621. this.rebuildInputCheck();
  45622. }
  45623. }
  45624. };
  45625. CameraInputsManager.prototype.removeByType = function (inputType) {
  45626. for (var cam in this.attached) {
  45627. var input = this.attached[cam];
  45628. if (input.getClassName() === inputType) {
  45629. input.detachControl(this.attachedElement);
  45630. input.camera = null;
  45631. delete this.attached[cam];
  45632. this.rebuildInputCheck();
  45633. }
  45634. }
  45635. };
  45636. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  45637. var current = this.checkInputs;
  45638. return function () {
  45639. current();
  45640. fn();
  45641. };
  45642. };
  45643. CameraInputsManager.prototype.attachInput = function (input) {
  45644. if (this.attachedElement) {
  45645. input.attachControl(this.attachedElement, this.noPreventDefault);
  45646. }
  45647. };
  45648. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  45649. if (noPreventDefault === void 0) { noPreventDefault = false; }
  45650. if (this.attachedElement) {
  45651. return;
  45652. }
  45653. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  45654. this.attachedElement = element;
  45655. this.noPreventDefault = noPreventDefault;
  45656. for (var cam in this.attached) {
  45657. this.attached[cam].attachControl(element, noPreventDefault);
  45658. }
  45659. };
  45660. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  45661. if (disconnect === void 0) { disconnect = false; }
  45662. if (this.attachedElement !== element) {
  45663. return;
  45664. }
  45665. for (var cam in this.attached) {
  45666. this.attached[cam].detachControl(element);
  45667. if (disconnect) {
  45668. this.attached[cam].camera = null;
  45669. }
  45670. }
  45671. this.attachedElement = null;
  45672. };
  45673. CameraInputsManager.prototype.rebuildInputCheck = function () {
  45674. this.checkInputs = function () { };
  45675. for (var cam in this.attached) {
  45676. var input = this.attached[cam];
  45677. if (input.checkInputs) {
  45678. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45679. }
  45680. }
  45681. };
  45682. /**
  45683. * Remove all attached input methods from a camera
  45684. */
  45685. CameraInputsManager.prototype.clear = function () {
  45686. if (this.attachedElement) {
  45687. this.detachElement(this.attachedElement, true);
  45688. }
  45689. this.attached = {};
  45690. this.attachedElement = null;
  45691. this.checkInputs = function () { };
  45692. };
  45693. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  45694. var inputs = {};
  45695. for (var cam in this.attached) {
  45696. var input = this.attached[cam];
  45697. var res = BABYLON.SerializationHelper.Serialize(input);
  45698. inputs[input.getClassName()] = res;
  45699. }
  45700. serializedCamera.inputsmgr = inputs;
  45701. };
  45702. CameraInputsManager.prototype.parse = function (parsedCamera) {
  45703. var parsedInputs = parsedCamera.inputsmgr;
  45704. if (parsedInputs) {
  45705. this.clear();
  45706. for (var n in parsedInputs) {
  45707. var construct = BABYLON.CameraInputTypes[n];
  45708. if (construct) {
  45709. var parsedinput = parsedInputs[n];
  45710. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  45711. this.add(input);
  45712. }
  45713. }
  45714. }
  45715. else {
  45716. //2016-03-08 this part is for managing backward compatibility
  45717. for (var n in this.attached) {
  45718. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  45719. if (construct) {
  45720. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  45721. this.remove(this.attached[n]);
  45722. this.add(input);
  45723. }
  45724. }
  45725. }
  45726. };
  45727. return CameraInputsManager;
  45728. }());
  45729. BABYLON.CameraInputsManager = CameraInputsManager;
  45730. })(BABYLON || (BABYLON = {}));
  45731. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  45732. "use strict";
  45733. var BABYLON;
  45734. (function (BABYLON) {
  45735. var TargetCamera = /** @class */ (function (_super) {
  45736. __extends(TargetCamera, _super);
  45737. function TargetCamera(name, position, scene) {
  45738. var _this = _super.call(this, name, position, scene) || this;
  45739. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  45740. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  45741. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  45742. _this.speed = 2.0;
  45743. _this.noRotationConstraint = false;
  45744. _this.lockedTarget = null;
  45745. _this._currentTarget = BABYLON.Vector3.Zero();
  45746. _this._viewMatrix = BABYLON.Matrix.Zero();
  45747. _this._camMatrix = BABYLON.Matrix.Zero();
  45748. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  45749. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  45750. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  45751. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  45752. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  45753. _this._lookAtTemp = BABYLON.Matrix.Zero();
  45754. _this._tempMatrix = BABYLON.Matrix.Zero();
  45755. return _this;
  45756. }
  45757. TargetCamera.prototype.getFrontPosition = function (distance) {
  45758. this.getWorldMatrix();
  45759. var direction = this.getTarget().subtract(this.position);
  45760. direction.normalize();
  45761. direction.scaleInPlace(distance);
  45762. return this.globalPosition.add(direction);
  45763. };
  45764. TargetCamera.prototype._getLockedTargetPosition = function () {
  45765. if (!this.lockedTarget) {
  45766. return null;
  45767. }
  45768. if (this.lockedTarget.absolutePosition) {
  45769. this.lockedTarget.computeWorldMatrix();
  45770. }
  45771. return this.lockedTarget.absolutePosition || this.lockedTarget;
  45772. };
  45773. TargetCamera.prototype.storeState = function () {
  45774. this._storedPosition = this.position.clone();
  45775. this._storedRotation = this.rotation.clone();
  45776. if (this.rotationQuaternion) {
  45777. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  45778. }
  45779. return _super.prototype.storeState.call(this);
  45780. };
  45781. /**
  45782. * Restored camera state. You must call storeState() first
  45783. */
  45784. TargetCamera.prototype._restoreStateValues = function () {
  45785. if (!_super.prototype._restoreStateValues.call(this)) {
  45786. return false;
  45787. }
  45788. this.position = this._storedPosition.clone();
  45789. this.rotation = this._storedRotation.clone();
  45790. if (this.rotationQuaternion) {
  45791. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  45792. }
  45793. this.cameraDirection.copyFromFloats(0, 0, 0);
  45794. this.cameraRotation.copyFromFloats(0, 0);
  45795. return true;
  45796. };
  45797. // Cache
  45798. TargetCamera.prototype._initCache = function () {
  45799. _super.prototype._initCache.call(this);
  45800. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45801. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45802. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45803. };
  45804. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  45805. if (!ignoreParentClass) {
  45806. _super.prototype._updateCache.call(this);
  45807. }
  45808. var lockedTargetPosition = this._getLockedTargetPosition();
  45809. if (!lockedTargetPosition) {
  45810. this._cache.lockedTarget = null;
  45811. }
  45812. else {
  45813. if (!this._cache.lockedTarget) {
  45814. this._cache.lockedTarget = lockedTargetPosition.clone();
  45815. }
  45816. else {
  45817. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  45818. }
  45819. }
  45820. this._cache.rotation.copyFrom(this.rotation);
  45821. if (this.rotationQuaternion)
  45822. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  45823. };
  45824. // Synchronized
  45825. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  45826. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  45827. return false;
  45828. }
  45829. var lockedTargetPosition = this._getLockedTargetPosition();
  45830. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  45831. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  45832. };
  45833. // Methods
  45834. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  45835. var engine = this.getEngine();
  45836. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  45837. };
  45838. // Target
  45839. TargetCamera.prototype.setTarget = function (target) {
  45840. this.upVector.normalize();
  45841. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  45842. this._camMatrix.invert();
  45843. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  45844. var vDir = target.subtract(this.position);
  45845. if (vDir.x >= 0.0) {
  45846. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  45847. }
  45848. else {
  45849. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  45850. }
  45851. this.rotation.z = 0;
  45852. if (isNaN(this.rotation.x)) {
  45853. this.rotation.x = 0;
  45854. }
  45855. if (isNaN(this.rotation.y)) {
  45856. this.rotation.y = 0;
  45857. }
  45858. if (isNaN(this.rotation.z)) {
  45859. this.rotation.z = 0;
  45860. }
  45861. if (this.rotationQuaternion) {
  45862. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  45863. }
  45864. };
  45865. /**
  45866. * Return the current target position of the camera. This value is expressed in local space.
  45867. */
  45868. TargetCamera.prototype.getTarget = function () {
  45869. return this._currentTarget;
  45870. };
  45871. TargetCamera.prototype._decideIfNeedsToMove = function () {
  45872. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  45873. };
  45874. TargetCamera.prototype._updatePosition = function () {
  45875. if (this.parent) {
  45876. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  45877. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  45878. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  45879. return;
  45880. }
  45881. this.position.addInPlace(this.cameraDirection);
  45882. };
  45883. TargetCamera.prototype._checkInputs = function () {
  45884. var needToMove = this._decideIfNeedsToMove();
  45885. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  45886. // Move
  45887. if (needToMove) {
  45888. this._updatePosition();
  45889. }
  45890. // Rotate
  45891. if (needToRotate) {
  45892. this.rotation.x += this.cameraRotation.x;
  45893. this.rotation.y += this.cameraRotation.y;
  45894. //rotate, if quaternion is set and rotation was used
  45895. if (this.rotationQuaternion) {
  45896. var len = this.rotation.lengthSquared();
  45897. if (len) {
  45898. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  45899. }
  45900. }
  45901. if (!this.noRotationConstraint) {
  45902. var limit = (Math.PI / 2) * 0.95;
  45903. if (this.rotation.x > limit)
  45904. this.rotation.x = limit;
  45905. if (this.rotation.x < -limit)
  45906. this.rotation.x = -limit;
  45907. }
  45908. }
  45909. // Inertia
  45910. if (needToMove) {
  45911. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  45912. this.cameraDirection.x = 0;
  45913. }
  45914. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  45915. this.cameraDirection.y = 0;
  45916. }
  45917. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  45918. this.cameraDirection.z = 0;
  45919. }
  45920. this.cameraDirection.scaleInPlace(this.inertia);
  45921. }
  45922. if (needToRotate) {
  45923. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  45924. this.cameraRotation.x = 0;
  45925. }
  45926. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  45927. this.cameraRotation.y = 0;
  45928. }
  45929. this.cameraRotation.scaleInPlace(this.inertia);
  45930. }
  45931. _super.prototype._checkInputs.call(this);
  45932. };
  45933. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  45934. if (this.rotationQuaternion) {
  45935. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  45936. }
  45937. else {
  45938. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  45939. }
  45940. //update the up vector!
  45941. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  45942. };
  45943. TargetCamera.prototype._getViewMatrix = function () {
  45944. if (this.lockedTarget) {
  45945. this.setTarget(this._getLockedTargetPosition());
  45946. }
  45947. // Compute
  45948. this._updateCameraRotationMatrix();
  45949. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  45950. // Computing target and final matrix
  45951. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  45952. if (this.getScene().useRightHandedSystem) {
  45953. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  45954. }
  45955. else {
  45956. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  45957. }
  45958. return this._viewMatrix;
  45959. };
  45960. /**
  45961. * @override
  45962. * Override Camera.createRigCamera
  45963. */
  45964. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  45965. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  45966. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  45967. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  45968. if (!this.rotationQuaternion) {
  45969. this.rotationQuaternion = new BABYLON.Quaternion();
  45970. }
  45971. rigCamera._cameraRigParams = {};
  45972. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  45973. }
  45974. return rigCamera;
  45975. }
  45976. return null;
  45977. };
  45978. /**
  45979. * @override
  45980. * Override Camera._updateRigCameras
  45981. */
  45982. TargetCamera.prototype._updateRigCameras = function () {
  45983. var camLeft = this._rigCameras[0];
  45984. var camRight = this._rigCameras[1];
  45985. switch (this.cameraRigMode) {
  45986. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45987. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45988. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45989. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45990. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  45991. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  45992. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  45993. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  45994. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  45995. camLeft.setTarget(this.getTarget());
  45996. camRight.setTarget(this.getTarget());
  45997. break;
  45998. case BABYLON.Camera.RIG_MODE_VR:
  45999. if (camLeft.rotationQuaternion) {
  46000. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46001. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46002. }
  46003. else {
  46004. camLeft.rotation.copyFrom(this.rotation);
  46005. camRight.rotation.copyFrom(this.rotation);
  46006. }
  46007. camLeft.position.copyFrom(this.position);
  46008. camRight.position.copyFrom(this.position);
  46009. break;
  46010. }
  46011. _super.prototype._updateRigCameras.call(this);
  46012. };
  46013. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46014. if (!this._rigCamTransformMatrix) {
  46015. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46016. }
  46017. var target = this.getTarget();
  46018. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46019. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46020. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46021. };
  46022. TargetCamera.prototype.getClassName = function () {
  46023. return "TargetCamera";
  46024. };
  46025. __decorate([
  46026. BABYLON.serializeAsVector3()
  46027. ], TargetCamera.prototype, "rotation", void 0);
  46028. __decorate([
  46029. BABYLON.serialize()
  46030. ], TargetCamera.prototype, "speed", void 0);
  46031. __decorate([
  46032. BABYLON.serializeAsMeshReference("lockedTargetId")
  46033. ], TargetCamera.prototype, "lockedTarget", void 0);
  46034. return TargetCamera;
  46035. }(BABYLON.Camera));
  46036. BABYLON.TargetCamera = TargetCamera;
  46037. })(BABYLON || (BABYLON = {}));
  46038. //# sourceMappingURL=babylon.targetCamera.js.map
  46039. "use strict";
  46040. var BABYLON;
  46041. (function (BABYLON) {
  46042. var FreeCameraMouseInput = /** @class */ (function () {
  46043. function FreeCameraMouseInput(touchEnabled) {
  46044. if (touchEnabled === void 0) { touchEnabled = true; }
  46045. this.touchEnabled = touchEnabled;
  46046. this.buttons = [0, 1, 2];
  46047. this.angularSensibility = 2000.0;
  46048. this.previousPosition = null;
  46049. }
  46050. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46051. var _this = this;
  46052. var engine = this.camera.getEngine();
  46053. if (!this._pointerInput) {
  46054. this._pointerInput = function (p, s) {
  46055. var evt = p.event;
  46056. if (engine.isInVRExclusivePointerMode) {
  46057. return;
  46058. }
  46059. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46060. return;
  46061. }
  46062. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46063. return;
  46064. }
  46065. var srcElement = (evt.srcElement || evt.target);
  46066. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46067. try {
  46068. srcElement.setPointerCapture(evt.pointerId);
  46069. }
  46070. catch (e) {
  46071. //Nothing to do with the error. Execution will continue.
  46072. }
  46073. _this.previousPosition = {
  46074. x: evt.clientX,
  46075. y: evt.clientY
  46076. };
  46077. if (!noPreventDefault) {
  46078. evt.preventDefault();
  46079. element.focus();
  46080. }
  46081. }
  46082. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46083. try {
  46084. srcElement.releasePointerCapture(evt.pointerId);
  46085. }
  46086. catch (e) {
  46087. //Nothing to do with the error.
  46088. }
  46089. _this.previousPosition = null;
  46090. if (!noPreventDefault) {
  46091. evt.preventDefault();
  46092. }
  46093. }
  46094. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46095. if (!_this.previousPosition || engine.isPointerLock) {
  46096. return;
  46097. }
  46098. var offsetX = evt.clientX - _this.previousPosition.x;
  46099. var offsetY = evt.clientY - _this.previousPosition.y;
  46100. if (_this.camera.getScene().useRightHandedSystem) {
  46101. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  46102. }
  46103. else {
  46104. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46105. }
  46106. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46107. _this.previousPosition = {
  46108. x: evt.clientX,
  46109. y: evt.clientY
  46110. };
  46111. if (!noPreventDefault) {
  46112. evt.preventDefault();
  46113. }
  46114. }
  46115. };
  46116. }
  46117. this._onMouseMove = function (evt) {
  46118. if (!engine.isPointerLock) {
  46119. return;
  46120. }
  46121. if (engine.isInVRExclusivePointerMode) {
  46122. return;
  46123. }
  46124. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46125. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46126. if (_this.camera.getScene().useRightHandedSystem) {
  46127. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  46128. }
  46129. else {
  46130. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46131. }
  46132. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46133. _this.previousPosition = null;
  46134. if (!noPreventDefault) {
  46135. evt.preventDefault();
  46136. }
  46137. };
  46138. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46139. element.addEventListener("mousemove", this._onMouseMove, false);
  46140. };
  46141. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46142. if (this._observer && element) {
  46143. this.camera.getScene().onPointerObservable.remove(this._observer);
  46144. if (this._onMouseMove) {
  46145. element.removeEventListener("mousemove", this._onMouseMove);
  46146. }
  46147. this._observer = null;
  46148. this._onMouseMove = null;
  46149. this.previousPosition = null;
  46150. }
  46151. };
  46152. FreeCameraMouseInput.prototype.getClassName = function () {
  46153. return "FreeCameraMouseInput";
  46154. };
  46155. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46156. return "mouse";
  46157. };
  46158. __decorate([
  46159. BABYLON.serialize()
  46160. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46161. __decorate([
  46162. BABYLON.serialize()
  46163. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46164. return FreeCameraMouseInput;
  46165. }());
  46166. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46167. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46168. })(BABYLON || (BABYLON = {}));
  46169. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46170. "use strict";
  46171. var BABYLON;
  46172. (function (BABYLON) {
  46173. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46174. function FreeCameraKeyboardMoveInput() {
  46175. this._keys = new Array();
  46176. this.keysUp = [38];
  46177. this.keysDown = [40];
  46178. this.keysLeft = [37];
  46179. this.keysRight = [39];
  46180. }
  46181. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46182. var _this = this;
  46183. if (this._onCanvasBlurObserver) {
  46184. return;
  46185. }
  46186. this._scene = this.camera.getScene();
  46187. this._engine = this._scene.getEngine();
  46188. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46189. _this._keys = [];
  46190. });
  46191. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46192. var evt = info.event;
  46193. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46194. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46195. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46196. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46197. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46198. var index = _this._keys.indexOf(evt.keyCode);
  46199. if (index === -1) {
  46200. _this._keys.push(evt.keyCode);
  46201. }
  46202. if (!noPreventDefault) {
  46203. evt.preventDefault();
  46204. }
  46205. }
  46206. }
  46207. else {
  46208. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46209. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46210. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46211. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46212. var index = _this._keys.indexOf(evt.keyCode);
  46213. if (index >= 0) {
  46214. _this._keys.splice(index, 1);
  46215. }
  46216. if (!noPreventDefault) {
  46217. evt.preventDefault();
  46218. }
  46219. }
  46220. }
  46221. });
  46222. };
  46223. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46224. if (this._scene) {
  46225. if (this._onKeyboardObserver) {
  46226. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46227. }
  46228. if (this._onCanvasBlurObserver) {
  46229. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46230. }
  46231. this._onKeyboardObserver = null;
  46232. this._onCanvasBlurObserver = null;
  46233. }
  46234. this._keys = [];
  46235. };
  46236. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46237. if (this._onKeyboardObserver) {
  46238. var camera = this.camera;
  46239. // Keyboard
  46240. for (var index = 0; index < this._keys.length; index++) {
  46241. var keyCode = this._keys[index];
  46242. var speed = camera._computeLocalCameraSpeed();
  46243. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46244. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46245. }
  46246. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46247. camera._localDirection.copyFromFloats(0, 0, speed);
  46248. }
  46249. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46250. camera._localDirection.copyFromFloats(speed, 0, 0);
  46251. }
  46252. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46253. camera._localDirection.copyFromFloats(0, 0, -speed);
  46254. }
  46255. if (camera.getScene().useRightHandedSystem) {
  46256. camera._localDirection.z *= -1;
  46257. }
  46258. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46259. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46260. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46261. }
  46262. }
  46263. };
  46264. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46265. return "FreeCameraKeyboardMoveInput";
  46266. };
  46267. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46268. this._keys = [];
  46269. };
  46270. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46271. return "keyboard";
  46272. };
  46273. __decorate([
  46274. BABYLON.serialize()
  46275. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46276. __decorate([
  46277. BABYLON.serialize()
  46278. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46279. __decorate([
  46280. BABYLON.serialize()
  46281. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46282. __decorate([
  46283. BABYLON.serialize()
  46284. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46285. return FreeCameraKeyboardMoveInput;
  46286. }());
  46287. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46288. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46289. })(BABYLON || (BABYLON = {}));
  46290. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46291. "use strict";
  46292. var BABYLON;
  46293. (function (BABYLON) {
  46294. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46295. __extends(FreeCameraInputsManager, _super);
  46296. function FreeCameraInputsManager(camera) {
  46297. return _super.call(this, camera) || this;
  46298. }
  46299. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46300. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46301. return this;
  46302. };
  46303. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46304. if (touchEnabled === void 0) { touchEnabled = true; }
  46305. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46306. return this;
  46307. };
  46308. FreeCameraInputsManager.prototype.addGamepad = function () {
  46309. this.add(new BABYLON.FreeCameraGamepadInput());
  46310. return this;
  46311. };
  46312. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46313. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46314. return this;
  46315. };
  46316. FreeCameraInputsManager.prototype.addTouch = function () {
  46317. this.add(new BABYLON.FreeCameraTouchInput());
  46318. return this;
  46319. };
  46320. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  46321. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  46322. return this;
  46323. };
  46324. return FreeCameraInputsManager;
  46325. }(BABYLON.CameraInputsManager));
  46326. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  46327. })(BABYLON || (BABYLON = {}));
  46328. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  46329. "use strict";
  46330. var BABYLON;
  46331. (function (BABYLON) {
  46332. var FreeCamera = /** @class */ (function (_super) {
  46333. __extends(FreeCamera, _super);
  46334. function FreeCamera(name, position, scene) {
  46335. var _this = _super.call(this, name, position, scene) || this;
  46336. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  46337. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  46338. _this.checkCollisions = false;
  46339. _this.applyGravity = false;
  46340. _this._needMoveForGravity = false;
  46341. _this._oldPosition = BABYLON.Vector3.Zero();
  46342. _this._diffPosition = BABYLON.Vector3.Zero();
  46343. _this._newPosition = BABYLON.Vector3.Zero();
  46344. // Collisions
  46345. _this._collisionMask = -1;
  46346. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46347. if (collidedMesh === void 0) { collidedMesh = null; }
  46348. //TODO move this to the collision coordinator!
  46349. if (_this.getScene().workerCollisions)
  46350. newPosition.multiplyInPlace(_this._collider._radius);
  46351. var updatePosition = function (newPos) {
  46352. _this._newPosition.copyFrom(newPos);
  46353. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  46354. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  46355. _this.position.addInPlace(_this._diffPosition);
  46356. if (_this.onCollide && collidedMesh) {
  46357. _this.onCollide(collidedMesh);
  46358. }
  46359. }
  46360. };
  46361. updatePosition(newPosition);
  46362. };
  46363. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  46364. _this.inputs.addKeyboard().addMouse();
  46365. return _this;
  46366. }
  46367. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  46368. //-- begin properties for backward compatibility for inputs
  46369. /**
  46370. * Gets the input sensibility for a mouse input. (default is 2000.0)
  46371. * Higher values reduce sensitivity.
  46372. */
  46373. get: function () {
  46374. var mouse = this.inputs.attached["mouse"];
  46375. if (mouse)
  46376. return mouse.angularSensibility;
  46377. return 0;
  46378. },
  46379. /**
  46380. * Sets the input sensibility for a mouse input. (default is 2000.0)
  46381. * Higher values reduce sensitivity.
  46382. */
  46383. set: function (value) {
  46384. var mouse = this.inputs.attached["mouse"];
  46385. if (mouse)
  46386. mouse.angularSensibility = value;
  46387. },
  46388. enumerable: true,
  46389. configurable: true
  46390. });
  46391. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  46392. get: function () {
  46393. var keyboard = this.inputs.attached["keyboard"];
  46394. if (keyboard)
  46395. return keyboard.keysUp;
  46396. return [];
  46397. },
  46398. set: function (value) {
  46399. var keyboard = this.inputs.attached["keyboard"];
  46400. if (keyboard)
  46401. keyboard.keysUp = value;
  46402. },
  46403. enumerable: true,
  46404. configurable: true
  46405. });
  46406. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  46407. get: function () {
  46408. var keyboard = this.inputs.attached["keyboard"];
  46409. if (keyboard)
  46410. return keyboard.keysDown;
  46411. return [];
  46412. },
  46413. set: function (value) {
  46414. var keyboard = this.inputs.attached["keyboard"];
  46415. if (keyboard)
  46416. keyboard.keysDown = value;
  46417. },
  46418. enumerable: true,
  46419. configurable: true
  46420. });
  46421. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  46422. get: function () {
  46423. var keyboard = this.inputs.attached["keyboard"];
  46424. if (keyboard)
  46425. return keyboard.keysLeft;
  46426. return [];
  46427. },
  46428. set: function (value) {
  46429. var keyboard = this.inputs.attached["keyboard"];
  46430. if (keyboard)
  46431. keyboard.keysLeft = value;
  46432. },
  46433. enumerable: true,
  46434. configurable: true
  46435. });
  46436. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  46437. get: function () {
  46438. var keyboard = this.inputs.attached["keyboard"];
  46439. if (keyboard)
  46440. return keyboard.keysRight;
  46441. return [];
  46442. },
  46443. set: function (value) {
  46444. var keyboard = this.inputs.attached["keyboard"];
  46445. if (keyboard)
  46446. keyboard.keysRight = value;
  46447. },
  46448. enumerable: true,
  46449. configurable: true
  46450. });
  46451. // Controls
  46452. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  46453. this.inputs.attachElement(element, noPreventDefault);
  46454. };
  46455. FreeCamera.prototype.detachControl = function (element) {
  46456. this.inputs.detachElement(element);
  46457. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46458. this.cameraRotation = new BABYLON.Vector2(0, 0);
  46459. };
  46460. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  46461. get: function () {
  46462. return this._collisionMask;
  46463. },
  46464. set: function (mask) {
  46465. this._collisionMask = !isNaN(mask) ? mask : -1;
  46466. },
  46467. enumerable: true,
  46468. configurable: true
  46469. });
  46470. FreeCamera.prototype._collideWithWorld = function (displacement) {
  46471. var globalPosition;
  46472. if (this.parent) {
  46473. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  46474. }
  46475. else {
  46476. globalPosition = this.position;
  46477. }
  46478. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  46479. this._oldPosition.addInPlace(this.ellipsoidOffset);
  46480. if (!this._collider) {
  46481. this._collider = new BABYLON.Collider();
  46482. }
  46483. this._collider._radius = this.ellipsoid;
  46484. this._collider.collisionMask = this._collisionMask;
  46485. //no need for clone, as long as gravity is not on.
  46486. var actualDisplacement = displacement;
  46487. //add gravity to the direction to prevent the dual-collision checking
  46488. if (this.applyGravity) {
  46489. //this prevents mending with cameraDirection, a global variable of the free camera class.
  46490. actualDisplacement = displacement.add(this.getScene().gravity);
  46491. }
  46492. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  46493. };
  46494. FreeCamera.prototype._checkInputs = function () {
  46495. if (!this._localDirection) {
  46496. this._localDirection = BABYLON.Vector3.Zero();
  46497. this._transformedDirection = BABYLON.Vector3.Zero();
  46498. }
  46499. this.inputs.checkInputs();
  46500. _super.prototype._checkInputs.call(this);
  46501. };
  46502. FreeCamera.prototype._decideIfNeedsToMove = function () {
  46503. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46504. };
  46505. FreeCamera.prototype._updatePosition = function () {
  46506. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  46507. this._collideWithWorld(this.cameraDirection);
  46508. }
  46509. else {
  46510. _super.prototype._updatePosition.call(this);
  46511. }
  46512. };
  46513. FreeCamera.prototype.dispose = function () {
  46514. this.inputs.clear();
  46515. _super.prototype.dispose.call(this);
  46516. };
  46517. FreeCamera.prototype.getClassName = function () {
  46518. return "FreeCamera";
  46519. };
  46520. __decorate([
  46521. BABYLON.serializeAsVector3()
  46522. ], FreeCamera.prototype, "ellipsoid", void 0);
  46523. __decorate([
  46524. BABYLON.serializeAsVector3()
  46525. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  46526. __decorate([
  46527. BABYLON.serialize()
  46528. ], FreeCamera.prototype, "checkCollisions", void 0);
  46529. __decorate([
  46530. BABYLON.serialize()
  46531. ], FreeCamera.prototype, "applyGravity", void 0);
  46532. return FreeCamera;
  46533. }(BABYLON.TargetCamera));
  46534. BABYLON.FreeCamera = FreeCamera;
  46535. })(BABYLON || (BABYLON = {}));
  46536. //# sourceMappingURL=babylon.freeCamera.js.map
  46537. "use strict";
  46538. var BABYLON;
  46539. (function (BABYLON) {
  46540. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  46541. function ArcRotateCameraKeyboardMoveInput() {
  46542. this._keys = new Array();
  46543. this.keysUp = [38];
  46544. this.keysDown = [40];
  46545. this.keysLeft = [37];
  46546. this.keysRight = [39];
  46547. this.keysReset = [220];
  46548. this.panningSensibility = 50.0;
  46549. this.zoomingSensibility = 25.0;
  46550. this.useAltToZoom = true;
  46551. }
  46552. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46553. var _this = this;
  46554. if (this._onCanvasBlurObserver) {
  46555. return;
  46556. }
  46557. this._scene = this.camera.getScene();
  46558. this._engine = this._scene.getEngine();
  46559. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46560. _this._keys = [];
  46561. });
  46562. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46563. var evt = info.event;
  46564. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46565. _this._ctrlPressed = evt.ctrlKey;
  46566. _this._altPressed = evt.altKey;
  46567. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46568. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46569. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46570. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46571. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46572. var index = _this._keys.indexOf(evt.keyCode);
  46573. if (index === -1) {
  46574. _this._keys.push(evt.keyCode);
  46575. }
  46576. if (evt.preventDefault) {
  46577. if (!noPreventDefault) {
  46578. evt.preventDefault();
  46579. }
  46580. }
  46581. }
  46582. }
  46583. else {
  46584. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46585. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46586. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46587. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46588. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46589. var index = _this._keys.indexOf(evt.keyCode);
  46590. if (index >= 0) {
  46591. _this._keys.splice(index, 1);
  46592. }
  46593. if (evt.preventDefault) {
  46594. if (!noPreventDefault) {
  46595. evt.preventDefault();
  46596. }
  46597. }
  46598. }
  46599. }
  46600. });
  46601. };
  46602. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46603. if (this._scene) {
  46604. if (this._onKeyboardObserver) {
  46605. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46606. }
  46607. if (this._onCanvasBlurObserver) {
  46608. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46609. }
  46610. this._onKeyboardObserver = null;
  46611. this._onCanvasBlurObserver = null;
  46612. }
  46613. this._keys = [];
  46614. };
  46615. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46616. if (this._onKeyboardObserver) {
  46617. var camera = this.camera;
  46618. for (var index = 0; index < this._keys.length; index++) {
  46619. var keyCode = this._keys[index];
  46620. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46621. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46622. camera.inertialPanningX -= 1 / this.panningSensibility;
  46623. }
  46624. else {
  46625. camera.inertialAlphaOffset -= 0.01;
  46626. }
  46627. }
  46628. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46629. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46630. camera.inertialPanningY += 1 / this.panningSensibility;
  46631. }
  46632. else if (this._altPressed && this.useAltToZoom) {
  46633. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  46634. }
  46635. else {
  46636. camera.inertialBetaOffset -= 0.01;
  46637. }
  46638. }
  46639. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46640. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46641. camera.inertialPanningX += 1 / this.panningSensibility;
  46642. }
  46643. else {
  46644. camera.inertialAlphaOffset += 0.01;
  46645. }
  46646. }
  46647. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46648. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46649. camera.inertialPanningY -= 1 / this.panningSensibility;
  46650. }
  46651. else if (this._altPressed && this.useAltToZoom) {
  46652. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  46653. }
  46654. else {
  46655. camera.inertialBetaOffset += 0.01;
  46656. }
  46657. }
  46658. else if (this.keysReset.indexOf(keyCode) !== -1) {
  46659. camera.restoreState();
  46660. }
  46661. }
  46662. }
  46663. };
  46664. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  46665. return "ArcRotateCameraKeyboardMoveInput";
  46666. };
  46667. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46668. return "keyboard";
  46669. };
  46670. __decorate([
  46671. BABYLON.serialize()
  46672. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46673. __decorate([
  46674. BABYLON.serialize()
  46675. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46676. __decorate([
  46677. BABYLON.serialize()
  46678. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46679. __decorate([
  46680. BABYLON.serialize()
  46681. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46682. __decorate([
  46683. BABYLON.serialize()
  46684. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  46685. __decorate([
  46686. BABYLON.serialize()
  46687. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  46688. __decorate([
  46689. BABYLON.serialize()
  46690. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  46691. __decorate([
  46692. BABYLON.serialize()
  46693. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  46694. return ArcRotateCameraKeyboardMoveInput;
  46695. }());
  46696. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  46697. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  46698. })(BABYLON || (BABYLON = {}));
  46699. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  46700. "use strict";
  46701. var BABYLON;
  46702. (function (BABYLON) {
  46703. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  46704. function ArcRotateCameraMouseWheelInput() {
  46705. this.wheelPrecision = 3.0;
  46706. /**
  46707. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  46708. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  46709. */
  46710. this.wheelDeltaPercentage = 0;
  46711. }
  46712. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  46713. var _this = this;
  46714. this._wheel = function (p, s) {
  46715. //sanity check - this should be a PointerWheel event.
  46716. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  46717. return;
  46718. var event = p.event;
  46719. var delta = 0;
  46720. if (event.wheelDelta) {
  46721. if (_this.wheelDeltaPercentage) {
  46722. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  46723. if (event.wheelDelta > 0) {
  46724. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  46725. }
  46726. else {
  46727. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  46728. }
  46729. }
  46730. else {
  46731. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  46732. }
  46733. }
  46734. else if (event.detail) {
  46735. delta = -event.detail / _this.wheelPrecision;
  46736. }
  46737. if (delta)
  46738. _this.camera.inertialRadiusOffset += delta;
  46739. if (event.preventDefault) {
  46740. if (!noPreventDefault) {
  46741. event.preventDefault();
  46742. }
  46743. }
  46744. };
  46745. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  46746. };
  46747. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  46748. if (this._observer && element) {
  46749. this.camera.getScene().onPointerObservable.remove(this._observer);
  46750. this._observer = null;
  46751. this._wheel = null;
  46752. }
  46753. };
  46754. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  46755. return "ArcRotateCameraMouseWheelInput";
  46756. };
  46757. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  46758. return "mousewheel";
  46759. };
  46760. __decorate([
  46761. BABYLON.serialize()
  46762. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  46763. __decorate([
  46764. BABYLON.serialize()
  46765. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  46766. return ArcRotateCameraMouseWheelInput;
  46767. }());
  46768. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  46769. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  46770. })(BABYLON || (BABYLON = {}));
  46771. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  46772. "use strict";
  46773. var BABYLON;
  46774. (function (BABYLON) {
  46775. var ArcRotateCameraPointersInput = /** @class */ (function () {
  46776. function ArcRotateCameraPointersInput() {
  46777. this.buttons = [0, 1, 2];
  46778. this.angularSensibilityX = 1000.0;
  46779. this.angularSensibilityY = 1000.0;
  46780. this.pinchPrecision = 12.0;
  46781. /**
  46782. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  46783. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  46784. */
  46785. this.pinchDeltaPercentage = 0;
  46786. this.panningSensibility = 1000.0;
  46787. this.multiTouchPanning = true;
  46788. this.multiTouchPanAndZoom = true;
  46789. this._isPanClick = false;
  46790. this.pinchInwards = true;
  46791. }
  46792. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  46793. var _this = this;
  46794. var engine = this.camera.getEngine();
  46795. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  46796. var pointA = null;
  46797. var pointB = null;
  46798. var previousPinchSquaredDistance = 0;
  46799. var initialDistance = 0;
  46800. var twoFingerActivityCount = 0;
  46801. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  46802. this._pointerInput = function (p, s) {
  46803. var evt = p.event;
  46804. var isTouch = p.event.pointerType === "touch";
  46805. if (engine.isInVRExclusivePointerMode) {
  46806. return;
  46807. }
  46808. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46809. return;
  46810. }
  46811. var srcElement = (evt.srcElement || evt.target);
  46812. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46813. try {
  46814. srcElement.setPointerCapture(evt.pointerId);
  46815. }
  46816. catch (e) {
  46817. //Nothing to do with the error. Execution will continue.
  46818. }
  46819. // Manage panning with pan button click
  46820. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  46821. // manage pointers
  46822. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  46823. if (pointA === null) {
  46824. pointA = cacheSoloPointer;
  46825. }
  46826. else if (pointB === null) {
  46827. pointB = cacheSoloPointer;
  46828. }
  46829. if (!noPreventDefault) {
  46830. evt.preventDefault();
  46831. element.focus();
  46832. }
  46833. }
  46834. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  46835. _this.camera.restoreState();
  46836. }
  46837. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46838. try {
  46839. srcElement.releasePointerCapture(evt.pointerId);
  46840. }
  46841. catch (e) {
  46842. //Nothing to do with the error.
  46843. }
  46844. cacheSoloPointer = null;
  46845. previousPinchSquaredDistance = 0;
  46846. previousMultiTouchPanPosition.isPaning = false;
  46847. previousMultiTouchPanPosition.isPinching = false;
  46848. twoFingerActivityCount = 0;
  46849. initialDistance = 0;
  46850. if (!isTouch) {
  46851. pointB = null; // Mouse and pen are mono pointer
  46852. }
  46853. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  46854. //but emptying completly pointers collection is required to fix a bug on iPhone :
  46855. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  46856. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  46857. if (engine._badOS) {
  46858. pointA = pointB = null;
  46859. }
  46860. else {
  46861. //only remove the impacted pointer in case of multitouch allowing on most
  46862. //platforms switching from rotate to zoom and pan seamlessly.
  46863. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  46864. pointA = pointB;
  46865. pointB = null;
  46866. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  46867. }
  46868. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  46869. pointB = null;
  46870. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  46871. }
  46872. else {
  46873. pointA = pointB = null;
  46874. }
  46875. }
  46876. if (!noPreventDefault) {
  46877. evt.preventDefault();
  46878. }
  46879. }
  46880. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46881. if (!noPreventDefault) {
  46882. evt.preventDefault();
  46883. }
  46884. // One button down
  46885. if (pointA && pointB === null && cacheSoloPointer) {
  46886. if (_this.panningSensibility !== 0 &&
  46887. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  46888. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  46889. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  46890. }
  46891. else {
  46892. var offsetX = evt.clientX - cacheSoloPointer.x;
  46893. var offsetY = evt.clientY - cacheSoloPointer.y;
  46894. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  46895. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  46896. }
  46897. cacheSoloPointer.x = evt.clientX;
  46898. cacheSoloPointer.y = evt.clientY;
  46899. }
  46900. else if (pointA && pointB) {
  46901. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  46902. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  46903. ed.x = evt.clientX;
  46904. ed.y = evt.clientY;
  46905. var direction = _this.pinchInwards ? 1 : -1;
  46906. var distX = pointA.x - pointB.x;
  46907. var distY = pointA.y - pointB.y;
  46908. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  46909. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  46910. if (previousPinchSquaredDistance === 0) {
  46911. initialDistance = pinchDistance;
  46912. previousPinchSquaredDistance = pinchSquaredDistance;
  46913. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  46914. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  46915. return;
  46916. }
  46917. if (_this.multiTouchPanAndZoom) {
  46918. if (_this.pinchDeltaPercentage) {
  46919. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  46920. }
  46921. else {
  46922. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  46923. (_this.pinchPrecision *
  46924. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  46925. direction);
  46926. }
  46927. if (_this.panningSensibility !== 0) {
  46928. var pointersCenterX = (pointA.x + pointB.x) / 2;
  46929. var pointersCenterY = (pointA.y + pointB.y) / 2;
  46930. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  46931. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  46932. previousMultiTouchPanPosition.x = pointersCenterX;
  46933. previousMultiTouchPanPosition.y = pointersCenterY;
  46934. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  46935. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  46936. }
  46937. }
  46938. else {
  46939. twoFingerActivityCount++;
  46940. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  46941. if (_this.pinchDeltaPercentage) {
  46942. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  46943. }
  46944. else {
  46945. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  46946. (_this.pinchPrecision *
  46947. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  46948. direction);
  46949. }
  46950. previousMultiTouchPanPosition.isPaning = false;
  46951. previousMultiTouchPanPosition.isPinching = true;
  46952. }
  46953. else {
  46954. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  46955. if (!previousMultiTouchPanPosition.isPaning) {
  46956. previousMultiTouchPanPosition.isPaning = true;
  46957. previousMultiTouchPanPosition.isPinching = false;
  46958. previousMultiTouchPanPosition.x = ed.x;
  46959. previousMultiTouchPanPosition.y = ed.y;
  46960. return;
  46961. }
  46962. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  46963. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  46964. }
  46965. }
  46966. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  46967. previousMultiTouchPanPosition.x = ed.x;
  46968. previousMultiTouchPanPosition.y = ed.y;
  46969. }
  46970. }
  46971. previousPinchSquaredDistance = pinchSquaredDistance;
  46972. }
  46973. }
  46974. };
  46975. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  46976. this._onContextMenu = function (evt) {
  46977. evt.preventDefault();
  46978. };
  46979. if (!this.camera._useCtrlForPanning) {
  46980. element.addEventListener("contextmenu", this._onContextMenu, false);
  46981. }
  46982. this._onLostFocus = function () {
  46983. //this._keys = [];
  46984. pointA = pointB = null;
  46985. previousPinchSquaredDistance = 0;
  46986. previousMultiTouchPanPosition.isPaning = false;
  46987. previousMultiTouchPanPosition.isPinching = false;
  46988. twoFingerActivityCount = 0;
  46989. cacheSoloPointer = null;
  46990. initialDistance = 0;
  46991. };
  46992. this._onMouseMove = function (evt) {
  46993. if (!engine.isPointerLock) {
  46994. return;
  46995. }
  46996. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46997. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46998. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  46999. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47000. if (!noPreventDefault) {
  47001. evt.preventDefault();
  47002. }
  47003. };
  47004. this._onGestureStart = function (e) {
  47005. if (window.MSGesture === undefined) {
  47006. return;
  47007. }
  47008. if (!_this._MSGestureHandler) {
  47009. _this._MSGestureHandler = new MSGesture();
  47010. _this._MSGestureHandler.target = element;
  47011. }
  47012. _this._MSGestureHandler.addPointer(e.pointerId);
  47013. };
  47014. this._onGesture = function (e) {
  47015. _this.camera.radius *= e.scale;
  47016. if (e.preventDefault) {
  47017. if (!noPreventDefault) {
  47018. e.stopPropagation();
  47019. e.preventDefault();
  47020. }
  47021. }
  47022. };
  47023. element.addEventListener("mousemove", this._onMouseMove, false);
  47024. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47025. element.addEventListener("MSGestureChange", this._onGesture, false);
  47026. BABYLON.Tools.RegisterTopRootEvents([
  47027. { name: "blur", handler: this._onLostFocus }
  47028. ]);
  47029. };
  47030. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47031. if (this._onLostFocus) {
  47032. BABYLON.Tools.UnregisterTopRootEvents([
  47033. { name: "blur", handler: this._onLostFocus }
  47034. ]);
  47035. }
  47036. if (element && this._observer) {
  47037. this.camera.getScene().onPointerObservable.remove(this._observer);
  47038. this._observer = null;
  47039. if (this._onContextMenu) {
  47040. element.removeEventListener("contextmenu", this._onContextMenu);
  47041. }
  47042. if (this._onMouseMove) {
  47043. element.removeEventListener("mousemove", this._onMouseMove);
  47044. }
  47045. if (this._onGestureStart) {
  47046. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47047. }
  47048. if (this._onGesture) {
  47049. element.removeEventListener("MSGestureChange", this._onGesture);
  47050. }
  47051. this._isPanClick = false;
  47052. this.pinchInwards = true;
  47053. this._onMouseMove = null;
  47054. this._onGestureStart = null;
  47055. this._onGesture = null;
  47056. this._MSGestureHandler = null;
  47057. this._onLostFocus = null;
  47058. this._onContextMenu = null;
  47059. }
  47060. };
  47061. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47062. return "ArcRotateCameraPointersInput";
  47063. };
  47064. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47065. return "pointers";
  47066. };
  47067. __decorate([
  47068. BABYLON.serialize()
  47069. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47070. __decorate([
  47071. BABYLON.serialize()
  47072. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47073. __decorate([
  47074. BABYLON.serialize()
  47075. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47076. __decorate([
  47077. BABYLON.serialize()
  47078. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47079. __decorate([
  47080. BABYLON.serialize()
  47081. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47082. __decorate([
  47083. BABYLON.serialize()
  47084. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47085. __decorate([
  47086. BABYLON.serialize()
  47087. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47088. __decorate([
  47089. BABYLON.serialize()
  47090. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47091. return ArcRotateCameraPointersInput;
  47092. }());
  47093. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47094. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47095. })(BABYLON || (BABYLON = {}));
  47096. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47097. "use strict";
  47098. var BABYLON;
  47099. (function (BABYLON) {
  47100. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47101. __extends(ArcRotateCameraInputsManager, _super);
  47102. function ArcRotateCameraInputsManager(camera) {
  47103. return _super.call(this, camera) || this;
  47104. }
  47105. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47106. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47107. return this;
  47108. };
  47109. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47110. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47111. return this;
  47112. };
  47113. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47114. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47115. return this;
  47116. };
  47117. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  47118. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  47119. return this;
  47120. };
  47121. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47122. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47123. return this;
  47124. };
  47125. return ArcRotateCameraInputsManager;
  47126. }(BABYLON.CameraInputsManager));
  47127. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47128. })(BABYLON || (BABYLON = {}));
  47129. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47130. "use strict";
  47131. var BABYLON;
  47132. (function (BABYLON) {
  47133. var ArcRotateCamera = /** @class */ (function (_super) {
  47134. __extends(ArcRotateCamera, _super);
  47135. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  47136. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  47137. _this.inertialAlphaOffset = 0;
  47138. _this.inertialBetaOffset = 0;
  47139. _this.inertialRadiusOffset = 0;
  47140. _this.lowerAlphaLimit = null;
  47141. _this.upperAlphaLimit = null;
  47142. _this.lowerBetaLimit = 0.01;
  47143. _this.upperBetaLimit = Math.PI;
  47144. _this.lowerRadiusLimit = null;
  47145. _this.upperRadiusLimit = null;
  47146. _this.inertialPanningX = 0;
  47147. _this.inertialPanningY = 0;
  47148. _this.pinchToPanMaxDistance = 20;
  47149. _this.panningDistanceLimit = null;
  47150. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47151. _this.panningInertia = 0.9;
  47152. //-- end properties for backward compatibility for inputs
  47153. _this.zoomOnFactor = 1;
  47154. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47155. _this.allowUpsideDown = true;
  47156. _this._viewMatrix = new BABYLON.Matrix();
  47157. // Panning
  47158. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47159. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47160. _this.checkCollisions = false;
  47161. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47162. _this._previousPosition = BABYLON.Vector3.Zero();
  47163. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47164. _this._newPosition = BABYLON.Vector3.Zero();
  47165. _this._computationVector = BABYLON.Vector3.Zero();
  47166. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47167. if (collidedMesh === void 0) { collidedMesh = null; }
  47168. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47169. newPosition.multiplyInPlace(_this._collider._radius);
  47170. }
  47171. if (!collidedMesh) {
  47172. _this._previousPosition.copyFrom(_this.position);
  47173. }
  47174. else {
  47175. _this.setPosition(newPosition);
  47176. if (_this.onCollide) {
  47177. _this.onCollide(collidedMesh);
  47178. }
  47179. }
  47180. // Recompute because of constraints
  47181. var cosa = Math.cos(_this.alpha);
  47182. var sina = Math.sin(_this.alpha);
  47183. var cosb = Math.cos(_this.beta);
  47184. var sinb = Math.sin(_this.beta);
  47185. if (sinb === 0) {
  47186. sinb = 0.0001;
  47187. }
  47188. var target = _this._getTargetPosition();
  47189. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47190. target.addToRef(_this._computationVector, _this._newPosition);
  47191. _this.position.copyFrom(_this._newPosition);
  47192. var up = _this.upVector;
  47193. if (_this.allowUpsideDown && _this.beta < 0) {
  47194. up = up.clone();
  47195. up = up.negate();
  47196. }
  47197. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  47198. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47199. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47200. _this._collisionTriggered = false;
  47201. };
  47202. _this._target = BABYLON.Vector3.Zero();
  47203. if (target) {
  47204. _this.setTarget(target);
  47205. }
  47206. _this.alpha = alpha;
  47207. _this.beta = beta;
  47208. _this.radius = radius;
  47209. _this.getViewMatrix();
  47210. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47211. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47212. return _this;
  47213. }
  47214. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47215. get: function () {
  47216. return this._target;
  47217. },
  47218. set: function (value) {
  47219. this.setTarget(value);
  47220. },
  47221. enumerable: true,
  47222. configurable: true
  47223. });
  47224. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47225. //-- begin properties for backward compatibility for inputs
  47226. get: function () {
  47227. var pointers = this.inputs.attached["pointers"];
  47228. if (pointers)
  47229. return pointers.angularSensibilityX;
  47230. return 0;
  47231. },
  47232. set: function (value) {
  47233. var pointers = this.inputs.attached["pointers"];
  47234. if (pointers) {
  47235. pointers.angularSensibilityX = value;
  47236. }
  47237. },
  47238. enumerable: true,
  47239. configurable: true
  47240. });
  47241. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47242. get: function () {
  47243. var pointers = this.inputs.attached["pointers"];
  47244. if (pointers)
  47245. return pointers.angularSensibilityY;
  47246. return 0;
  47247. },
  47248. set: function (value) {
  47249. var pointers = this.inputs.attached["pointers"];
  47250. if (pointers) {
  47251. pointers.angularSensibilityY = value;
  47252. }
  47253. },
  47254. enumerable: true,
  47255. configurable: true
  47256. });
  47257. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47258. get: function () {
  47259. var pointers = this.inputs.attached["pointers"];
  47260. if (pointers)
  47261. return pointers.pinchPrecision;
  47262. return 0;
  47263. },
  47264. set: function (value) {
  47265. var pointers = this.inputs.attached["pointers"];
  47266. if (pointers) {
  47267. pointers.pinchPrecision = value;
  47268. }
  47269. },
  47270. enumerable: true,
  47271. configurable: true
  47272. });
  47273. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  47274. get: function () {
  47275. var pointers = this.inputs.attached["pointers"];
  47276. if (pointers)
  47277. return pointers.pinchDeltaPercentage;
  47278. return 0;
  47279. },
  47280. set: function (value) {
  47281. var pointers = this.inputs.attached["pointers"];
  47282. if (pointers) {
  47283. pointers.pinchDeltaPercentage = value;
  47284. }
  47285. },
  47286. enumerable: true,
  47287. configurable: true
  47288. });
  47289. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  47290. get: function () {
  47291. var pointers = this.inputs.attached["pointers"];
  47292. if (pointers)
  47293. return pointers.panningSensibility;
  47294. return 0;
  47295. },
  47296. set: function (value) {
  47297. var pointers = this.inputs.attached["pointers"];
  47298. if (pointers) {
  47299. pointers.panningSensibility = value;
  47300. }
  47301. },
  47302. enumerable: true,
  47303. configurable: true
  47304. });
  47305. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  47306. get: function () {
  47307. var keyboard = this.inputs.attached["keyboard"];
  47308. if (keyboard)
  47309. return keyboard.keysUp;
  47310. return [];
  47311. },
  47312. set: function (value) {
  47313. var keyboard = this.inputs.attached["keyboard"];
  47314. if (keyboard)
  47315. keyboard.keysUp = value;
  47316. },
  47317. enumerable: true,
  47318. configurable: true
  47319. });
  47320. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  47321. get: function () {
  47322. var keyboard = this.inputs.attached["keyboard"];
  47323. if (keyboard)
  47324. return keyboard.keysDown;
  47325. return [];
  47326. },
  47327. set: function (value) {
  47328. var keyboard = this.inputs.attached["keyboard"];
  47329. if (keyboard)
  47330. keyboard.keysDown = value;
  47331. },
  47332. enumerable: true,
  47333. configurable: true
  47334. });
  47335. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  47336. get: function () {
  47337. var keyboard = this.inputs.attached["keyboard"];
  47338. if (keyboard)
  47339. return keyboard.keysLeft;
  47340. return [];
  47341. },
  47342. set: function (value) {
  47343. var keyboard = this.inputs.attached["keyboard"];
  47344. if (keyboard)
  47345. keyboard.keysLeft = value;
  47346. },
  47347. enumerable: true,
  47348. configurable: true
  47349. });
  47350. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  47351. get: function () {
  47352. var keyboard = this.inputs.attached["keyboard"];
  47353. if (keyboard)
  47354. return keyboard.keysRight;
  47355. return [];
  47356. },
  47357. set: function (value) {
  47358. var keyboard = this.inputs.attached["keyboard"];
  47359. if (keyboard)
  47360. keyboard.keysRight = value;
  47361. },
  47362. enumerable: true,
  47363. configurable: true
  47364. });
  47365. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  47366. get: function () {
  47367. var mousewheel = this.inputs.attached["mousewheel"];
  47368. if (mousewheel)
  47369. return mousewheel.wheelPrecision;
  47370. return 0;
  47371. },
  47372. set: function (value) {
  47373. var mousewheel = this.inputs.attached["mousewheel"];
  47374. if (mousewheel)
  47375. mousewheel.wheelPrecision = value;
  47376. },
  47377. enumerable: true,
  47378. configurable: true
  47379. });
  47380. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  47381. get: function () {
  47382. var mousewheel = this.inputs.attached["mousewheel"];
  47383. if (mousewheel)
  47384. return mousewheel.wheelDeltaPercentage;
  47385. return 0;
  47386. },
  47387. set: function (value) {
  47388. var mousewheel = this.inputs.attached["mousewheel"];
  47389. if (mousewheel)
  47390. mousewheel.wheelDeltaPercentage = value;
  47391. },
  47392. enumerable: true,
  47393. configurable: true
  47394. });
  47395. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  47396. get: function () {
  47397. return this._bouncingBehavior;
  47398. },
  47399. enumerable: true,
  47400. configurable: true
  47401. });
  47402. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  47403. get: function () {
  47404. return this._bouncingBehavior != null;
  47405. },
  47406. set: function (value) {
  47407. if (value === this.useBouncingBehavior) {
  47408. return;
  47409. }
  47410. if (value) {
  47411. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  47412. this.addBehavior(this._bouncingBehavior);
  47413. }
  47414. else if (this._bouncingBehavior) {
  47415. this.removeBehavior(this._bouncingBehavior);
  47416. this._bouncingBehavior = null;
  47417. }
  47418. },
  47419. enumerable: true,
  47420. configurable: true
  47421. });
  47422. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  47423. get: function () {
  47424. return this._framingBehavior;
  47425. },
  47426. enumerable: true,
  47427. configurable: true
  47428. });
  47429. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  47430. get: function () {
  47431. return this._framingBehavior != null;
  47432. },
  47433. set: function (value) {
  47434. if (value === this.useFramingBehavior) {
  47435. return;
  47436. }
  47437. if (value) {
  47438. this._framingBehavior = new BABYLON.FramingBehavior();
  47439. this.addBehavior(this._framingBehavior);
  47440. }
  47441. else if (this._framingBehavior) {
  47442. this.removeBehavior(this._framingBehavior);
  47443. this._framingBehavior = null;
  47444. }
  47445. },
  47446. enumerable: true,
  47447. configurable: true
  47448. });
  47449. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  47450. get: function () {
  47451. return this._autoRotationBehavior;
  47452. },
  47453. enumerable: true,
  47454. configurable: true
  47455. });
  47456. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  47457. get: function () {
  47458. return this._autoRotationBehavior != null;
  47459. },
  47460. set: function (value) {
  47461. if (value === this.useAutoRotationBehavior) {
  47462. return;
  47463. }
  47464. if (value) {
  47465. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  47466. this.addBehavior(this._autoRotationBehavior);
  47467. }
  47468. else if (this._autoRotationBehavior) {
  47469. this.removeBehavior(this._autoRotationBehavior);
  47470. this._autoRotationBehavior = null;
  47471. }
  47472. },
  47473. enumerable: true,
  47474. configurable: true
  47475. });
  47476. // Cache
  47477. ArcRotateCamera.prototype._initCache = function () {
  47478. _super.prototype._initCache.call(this);
  47479. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47480. this._cache.alpha = undefined;
  47481. this._cache.beta = undefined;
  47482. this._cache.radius = undefined;
  47483. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  47484. };
  47485. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  47486. if (!ignoreParentClass) {
  47487. _super.prototype._updateCache.call(this);
  47488. }
  47489. this._cache._target.copyFrom(this._getTargetPosition());
  47490. this._cache.alpha = this.alpha;
  47491. this._cache.beta = this.beta;
  47492. this._cache.radius = this.radius;
  47493. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  47494. };
  47495. ArcRotateCamera.prototype._getTargetPosition = function () {
  47496. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  47497. var pos = this._targetHost.getAbsolutePosition();
  47498. if (this._targetBoundingCenter) {
  47499. pos.addToRef(this._targetBoundingCenter, this._target);
  47500. }
  47501. else {
  47502. this._target.copyFrom(pos);
  47503. }
  47504. }
  47505. var lockedTargetPosition = this._getLockedTargetPosition();
  47506. if (lockedTargetPosition) {
  47507. return lockedTargetPosition;
  47508. }
  47509. return this._target;
  47510. };
  47511. ArcRotateCamera.prototype.storeState = function () {
  47512. this._storedAlpha = this.alpha;
  47513. this._storedBeta = this.beta;
  47514. this._storedRadius = this.radius;
  47515. this._storedTarget = this._getTargetPosition().clone();
  47516. return _super.prototype.storeState.call(this);
  47517. };
  47518. /**
  47519. * Restored camera state. You must call storeState() first
  47520. */
  47521. ArcRotateCamera.prototype._restoreStateValues = function () {
  47522. if (!_super.prototype._restoreStateValues.call(this)) {
  47523. return false;
  47524. }
  47525. this.alpha = this._storedAlpha;
  47526. this.beta = this._storedBeta;
  47527. this.radius = this._storedRadius;
  47528. this.setTarget(this._storedTarget.clone());
  47529. this.inertialAlphaOffset = 0;
  47530. this.inertialBetaOffset = 0;
  47531. this.inertialRadiusOffset = 0;
  47532. this.inertialPanningX = 0;
  47533. this.inertialPanningY = 0;
  47534. return true;
  47535. };
  47536. // Synchronized
  47537. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  47538. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  47539. return false;
  47540. return this._cache._target.equals(this._getTargetPosition())
  47541. && this._cache.alpha === this.alpha
  47542. && this._cache.beta === this.beta
  47543. && this._cache.radius === this.radius
  47544. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  47545. };
  47546. // Methods
  47547. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  47548. var _this = this;
  47549. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  47550. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  47551. this._useCtrlForPanning = useCtrlForPanning;
  47552. this._panningMouseButton = panningMouseButton;
  47553. this.inputs.attachElement(element, noPreventDefault);
  47554. this._reset = function () {
  47555. _this.inertialAlphaOffset = 0;
  47556. _this.inertialBetaOffset = 0;
  47557. _this.inertialRadiusOffset = 0;
  47558. _this.inertialPanningX = 0;
  47559. _this.inertialPanningY = 0;
  47560. };
  47561. };
  47562. ArcRotateCamera.prototype.detachControl = function (element) {
  47563. this.inputs.detachElement(element);
  47564. if (this._reset) {
  47565. this._reset();
  47566. }
  47567. };
  47568. ArcRotateCamera.prototype._checkInputs = function () {
  47569. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  47570. if (this._collisionTriggered) {
  47571. return;
  47572. }
  47573. this.inputs.checkInputs();
  47574. // Inertia
  47575. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  47576. if (this.getScene().useRightHandedSystem) {
  47577. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  47578. }
  47579. else {
  47580. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  47581. }
  47582. this.beta += this.inertialBetaOffset;
  47583. this.radius -= this.inertialRadiusOffset;
  47584. this.inertialAlphaOffset *= this.inertia;
  47585. this.inertialBetaOffset *= this.inertia;
  47586. this.inertialRadiusOffset *= this.inertia;
  47587. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  47588. this.inertialAlphaOffset = 0;
  47589. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  47590. this.inertialBetaOffset = 0;
  47591. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  47592. this.inertialRadiusOffset = 0;
  47593. }
  47594. // Panning inertia
  47595. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  47596. if (!this._localDirection) {
  47597. this._localDirection = BABYLON.Vector3.Zero();
  47598. this._transformedDirection = BABYLON.Vector3.Zero();
  47599. }
  47600. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  47601. this._localDirection.multiplyInPlace(this.panningAxis);
  47602. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  47603. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  47604. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  47605. if (!this.panningAxis.y) {
  47606. this._transformedDirection.y = 0;
  47607. }
  47608. if (!this._targetHost) {
  47609. if (this.panningDistanceLimit) {
  47610. this._transformedDirection.addInPlace(this._target);
  47611. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  47612. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  47613. this._target.copyFrom(this._transformedDirection);
  47614. }
  47615. }
  47616. else {
  47617. this._target.addInPlace(this._transformedDirection);
  47618. }
  47619. }
  47620. this.inertialPanningX *= this.panningInertia;
  47621. this.inertialPanningY *= this.panningInertia;
  47622. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  47623. this.inertialPanningX = 0;
  47624. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  47625. this.inertialPanningY = 0;
  47626. }
  47627. // Limits
  47628. this._checkLimits();
  47629. _super.prototype._checkInputs.call(this);
  47630. };
  47631. ArcRotateCamera.prototype._checkLimits = function () {
  47632. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  47633. if (this.allowUpsideDown && this.beta > Math.PI) {
  47634. this.beta = this.beta - (2 * Math.PI);
  47635. }
  47636. }
  47637. else {
  47638. if (this.beta < this.lowerBetaLimit) {
  47639. this.beta = this.lowerBetaLimit;
  47640. }
  47641. }
  47642. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  47643. if (this.allowUpsideDown && this.beta < -Math.PI) {
  47644. this.beta = this.beta + (2 * Math.PI);
  47645. }
  47646. }
  47647. else {
  47648. if (this.beta > this.upperBetaLimit) {
  47649. this.beta = this.upperBetaLimit;
  47650. }
  47651. }
  47652. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  47653. this.alpha = this.lowerAlphaLimit;
  47654. }
  47655. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  47656. this.alpha = this.upperAlphaLimit;
  47657. }
  47658. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  47659. this.radius = this.lowerRadiusLimit;
  47660. }
  47661. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  47662. this.radius = this.upperRadiusLimit;
  47663. }
  47664. };
  47665. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  47666. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  47667. this.radius = this._computationVector.length();
  47668. if (this.radius === 0) {
  47669. this.radius = 0.0001; // Just to avoid division by zero
  47670. }
  47671. // Alpha
  47672. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  47673. if (this._computationVector.z < 0) {
  47674. this.alpha = 2 * Math.PI - this.alpha;
  47675. }
  47676. // Beta
  47677. this.beta = Math.acos(this._computationVector.y / this.radius);
  47678. this._checkLimits();
  47679. };
  47680. ArcRotateCamera.prototype.setPosition = function (position) {
  47681. if (this.position.equals(position)) {
  47682. return;
  47683. }
  47684. this.position.copyFrom(position);
  47685. this.rebuildAnglesAndRadius();
  47686. };
  47687. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  47688. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  47689. if (allowSamePosition === void 0) { allowSamePosition = false; }
  47690. if (target.getBoundingInfo) {
  47691. if (toBoundingCenter) {
  47692. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  47693. }
  47694. else {
  47695. this._targetBoundingCenter = null;
  47696. }
  47697. this._targetHost = target;
  47698. this._target = this._getTargetPosition();
  47699. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  47700. }
  47701. else {
  47702. var newTarget = target;
  47703. var currentTarget = this._getTargetPosition();
  47704. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  47705. return;
  47706. }
  47707. this._targetHost = null;
  47708. this._target = newTarget;
  47709. this._targetBoundingCenter = null;
  47710. this.onMeshTargetChangedObservable.notifyObservers(null);
  47711. }
  47712. this.rebuildAnglesAndRadius();
  47713. };
  47714. ArcRotateCamera.prototype._getViewMatrix = function () {
  47715. // Compute
  47716. var cosa = Math.cos(this.alpha);
  47717. var sina = Math.sin(this.alpha);
  47718. var cosb = Math.cos(this.beta);
  47719. var sinb = Math.sin(this.beta);
  47720. if (sinb === 0) {
  47721. sinb = 0.0001;
  47722. }
  47723. var target = this._getTargetPosition();
  47724. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  47725. target.addToRef(this._computationVector, this._newPosition);
  47726. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  47727. if (!this._collider) {
  47728. this._collider = new BABYLON.Collider();
  47729. }
  47730. this._collider._radius = this.collisionRadius;
  47731. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  47732. this._collisionTriggered = true;
  47733. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47734. }
  47735. else {
  47736. this.position.copyFrom(this._newPosition);
  47737. var up = this.upVector;
  47738. if (this.allowUpsideDown && sinb < 0) {
  47739. up = up.clone();
  47740. up = up.negate();
  47741. }
  47742. if (this.getScene().useRightHandedSystem) {
  47743. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  47744. }
  47745. else {
  47746. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  47747. }
  47748. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  47749. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  47750. }
  47751. this._currentTarget = target;
  47752. return this._viewMatrix;
  47753. };
  47754. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  47755. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  47756. meshes = meshes || this.getScene().meshes;
  47757. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  47758. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  47759. this.radius = distance * this.zoomOnFactor;
  47760. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  47761. };
  47762. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  47763. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  47764. var meshesOrMinMaxVector;
  47765. var distance;
  47766. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  47767. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  47768. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  47769. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  47770. }
  47771. else {
  47772. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  47773. meshesOrMinMaxVector = minMaxVectorAndDistance;
  47774. distance = minMaxVectorAndDistance.distance;
  47775. }
  47776. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  47777. if (!doNotUpdateMaxZ) {
  47778. this.maxZ = distance * 2;
  47779. }
  47780. };
  47781. /**
  47782. * @override
  47783. * Override Camera.createRigCamera
  47784. */
  47785. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47786. var alphaShift = 0;
  47787. switch (this.cameraRigMode) {
  47788. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47789. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47790. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47791. case BABYLON.Camera.RIG_MODE_VR:
  47792. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  47793. break;
  47794. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47795. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  47796. break;
  47797. }
  47798. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  47799. rigCam._cameraRigParams = {};
  47800. return rigCam;
  47801. };
  47802. /**
  47803. * @override
  47804. * Override Camera._updateRigCameras
  47805. */
  47806. ArcRotateCamera.prototype._updateRigCameras = function () {
  47807. var camLeft = this._rigCameras[0];
  47808. var camRight = this._rigCameras[1];
  47809. camLeft.beta = camRight.beta = this.beta;
  47810. camLeft.radius = camRight.radius = this.radius;
  47811. switch (this.cameraRigMode) {
  47812. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47813. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47814. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47815. case BABYLON.Camera.RIG_MODE_VR:
  47816. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  47817. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  47818. break;
  47819. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47820. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  47821. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  47822. break;
  47823. }
  47824. _super.prototype._updateRigCameras.call(this);
  47825. };
  47826. ArcRotateCamera.prototype.dispose = function () {
  47827. this.inputs.clear();
  47828. _super.prototype.dispose.call(this);
  47829. };
  47830. ArcRotateCamera.prototype.getClassName = function () {
  47831. return "ArcRotateCamera";
  47832. };
  47833. __decorate([
  47834. BABYLON.serialize()
  47835. ], ArcRotateCamera.prototype, "alpha", void 0);
  47836. __decorate([
  47837. BABYLON.serialize()
  47838. ], ArcRotateCamera.prototype, "beta", void 0);
  47839. __decorate([
  47840. BABYLON.serialize()
  47841. ], ArcRotateCamera.prototype, "radius", void 0);
  47842. __decorate([
  47843. BABYLON.serializeAsVector3("target")
  47844. ], ArcRotateCamera.prototype, "_target", void 0);
  47845. __decorate([
  47846. BABYLON.serialize()
  47847. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  47848. __decorate([
  47849. BABYLON.serialize()
  47850. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  47851. __decorate([
  47852. BABYLON.serialize()
  47853. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  47854. __decorate([
  47855. BABYLON.serialize()
  47856. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  47857. __decorate([
  47858. BABYLON.serialize()
  47859. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  47860. __decorate([
  47861. BABYLON.serialize()
  47862. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  47863. __decorate([
  47864. BABYLON.serialize()
  47865. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  47866. __decorate([
  47867. BABYLON.serialize()
  47868. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  47869. __decorate([
  47870. BABYLON.serialize()
  47871. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  47872. __decorate([
  47873. BABYLON.serialize()
  47874. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  47875. __decorate([
  47876. BABYLON.serialize()
  47877. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  47878. __decorate([
  47879. BABYLON.serialize()
  47880. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  47881. __decorate([
  47882. BABYLON.serialize()
  47883. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  47884. __decorate([
  47885. BABYLON.serializeAsVector3()
  47886. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  47887. __decorate([
  47888. BABYLON.serialize()
  47889. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  47890. __decorate([
  47891. BABYLON.serialize()
  47892. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  47893. __decorate([
  47894. BABYLON.serialize()
  47895. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  47896. return ArcRotateCamera;
  47897. }(BABYLON.TargetCamera));
  47898. BABYLON.ArcRotateCamera = ArcRotateCamera;
  47899. })(BABYLON || (BABYLON = {}));
  47900. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  47901. "use strict";
  47902. var BABYLON;
  47903. (function (BABYLON) {
  47904. /**
  47905. * The HemisphericLight simulates the ambient environment light,
  47906. * so the passed direction is the light reflection direction, not the incoming direction.
  47907. */
  47908. var HemisphericLight = /** @class */ (function (_super) {
  47909. __extends(HemisphericLight, _super);
  47910. /**
  47911. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  47912. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  47913. * The HemisphericLight can't cast shadows.
  47914. * Documentation : http://doc.babylonjs.com/tutorials/lights
  47915. * @param name The friendly name of the light
  47916. * @param direction The direction of the light reflection
  47917. * @param scene The scene the light belongs to
  47918. */
  47919. function HemisphericLight(name, direction, scene) {
  47920. var _this = _super.call(this, name, scene) || this;
  47921. /**
  47922. * The groundColor is the light in the opposite direction to the one specified during creation.
  47923. * 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.
  47924. */
  47925. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  47926. _this.direction = direction || BABYLON.Vector3.Up();
  47927. return _this;
  47928. }
  47929. HemisphericLight.prototype._buildUniformLayout = function () {
  47930. this._uniformBuffer.addUniform("vLightData", 4);
  47931. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  47932. this._uniformBuffer.addUniform("vLightSpecular", 3);
  47933. this._uniformBuffer.addUniform("vLightGround", 3);
  47934. this._uniformBuffer.addUniform("shadowsInfo", 3);
  47935. this._uniformBuffer.addUniform("depthValues", 2);
  47936. this._uniformBuffer.create();
  47937. };
  47938. /**
  47939. * Returns the string "HemisphericLight".
  47940. * @return The class name
  47941. */
  47942. HemisphericLight.prototype.getClassName = function () {
  47943. return "HemisphericLight";
  47944. };
  47945. /**
  47946. * Sets the HemisphericLight direction towards the passed target (Vector3).
  47947. * Returns the updated direction.
  47948. * @param target The target the direction should point to
  47949. * @return The computed direction
  47950. */
  47951. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  47952. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  47953. return this.direction;
  47954. };
  47955. /**
  47956. * Returns the shadow generator associated to the light.
  47957. * @returns Always null for hemispheric lights because it does not support shadows.
  47958. */
  47959. HemisphericLight.prototype.getShadowGenerator = function () {
  47960. return null;
  47961. };
  47962. /**
  47963. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  47964. * @param effect The effect to update
  47965. * @param lightIndex The index of the light in the effect to update
  47966. * @returns The hemispheric light
  47967. */
  47968. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  47969. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  47970. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  47971. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  47972. return this;
  47973. };
  47974. /**
  47975. * @ignore internal use only.
  47976. */
  47977. HemisphericLight.prototype._getWorldMatrix = function () {
  47978. if (!this._worldMatrix) {
  47979. this._worldMatrix = BABYLON.Matrix.Identity();
  47980. }
  47981. return this._worldMatrix;
  47982. };
  47983. /**
  47984. * Returns the integer 3.
  47985. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  47986. */
  47987. HemisphericLight.prototype.getTypeID = function () {
  47988. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  47989. };
  47990. __decorate([
  47991. BABYLON.serializeAsColor3()
  47992. ], HemisphericLight.prototype, "groundColor", void 0);
  47993. __decorate([
  47994. BABYLON.serializeAsVector3()
  47995. ], HemisphericLight.prototype, "direction", void 0);
  47996. return HemisphericLight;
  47997. }(BABYLON.Light));
  47998. BABYLON.HemisphericLight = HemisphericLight;
  47999. })(BABYLON || (BABYLON = {}));
  48000. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48001. "use strict";
  48002. var BABYLON;
  48003. (function (BABYLON) {
  48004. /**
  48005. * Base implementation IShadowLight
  48006. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48007. */
  48008. var ShadowLight = /** @class */ (function (_super) {
  48009. __extends(ShadowLight, _super);
  48010. function ShadowLight() {
  48011. var _this = _super !== null && _super.apply(this, arguments) || this;
  48012. _this._needProjectionMatrixCompute = true;
  48013. return _this;
  48014. }
  48015. ShadowLight.prototype._setPosition = function (value) {
  48016. this._position = value;
  48017. };
  48018. Object.defineProperty(ShadowLight.prototype, "position", {
  48019. /**
  48020. * Sets the position the shadow will be casted from. Also use as the light position for both
  48021. * point and spot lights.
  48022. */
  48023. get: function () {
  48024. return this._position;
  48025. },
  48026. /**
  48027. * Sets the position the shadow will be casted from. Also use as the light position for both
  48028. * point and spot lights.
  48029. */
  48030. set: function (value) {
  48031. this._setPosition(value);
  48032. },
  48033. enumerable: true,
  48034. configurable: true
  48035. });
  48036. ShadowLight.prototype._setDirection = function (value) {
  48037. this._direction = value;
  48038. };
  48039. Object.defineProperty(ShadowLight.prototype, "direction", {
  48040. /**
  48041. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48042. * Also use as the light direction on spot and directional lights.
  48043. */
  48044. get: function () {
  48045. return this._direction;
  48046. },
  48047. /**
  48048. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48049. * Also use as the light direction on spot and directional lights.
  48050. */
  48051. set: function (value) {
  48052. this._setDirection(value);
  48053. },
  48054. enumerable: true,
  48055. configurable: true
  48056. });
  48057. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48058. /**
  48059. * Gets the shadow projection clipping minimum z value.
  48060. */
  48061. get: function () {
  48062. return this._shadowMinZ;
  48063. },
  48064. /**
  48065. * Sets the shadow projection clipping minimum z value.
  48066. */
  48067. set: function (value) {
  48068. this._shadowMinZ = value;
  48069. this.forceProjectionMatrixCompute();
  48070. },
  48071. enumerable: true,
  48072. configurable: true
  48073. });
  48074. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48075. /**
  48076. * Sets the shadow projection clipping maximum z value.
  48077. */
  48078. get: function () {
  48079. return this._shadowMaxZ;
  48080. },
  48081. /**
  48082. * Gets the shadow projection clipping maximum z value.
  48083. */
  48084. set: function (value) {
  48085. this._shadowMaxZ = value;
  48086. this.forceProjectionMatrixCompute();
  48087. },
  48088. enumerable: true,
  48089. configurable: true
  48090. });
  48091. /**
  48092. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48093. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48094. */
  48095. ShadowLight.prototype.computeTransformedInformation = function () {
  48096. if (this.parent && this.parent.getWorldMatrix) {
  48097. if (!this.transformedPosition) {
  48098. this.transformedPosition = BABYLON.Vector3.Zero();
  48099. }
  48100. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48101. // In case the direction is present.
  48102. if (this.direction) {
  48103. if (!this.transformedDirection) {
  48104. this.transformedDirection = BABYLON.Vector3.Zero();
  48105. }
  48106. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48107. }
  48108. return true;
  48109. }
  48110. return false;
  48111. };
  48112. /**
  48113. * Return the depth scale used for the shadow map.
  48114. * @returns the depth scale.
  48115. */
  48116. ShadowLight.prototype.getDepthScale = function () {
  48117. return 50.0;
  48118. };
  48119. /**
  48120. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48121. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48122. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48123. */
  48124. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48125. return this.transformedDirection ? this.transformedDirection : this.direction;
  48126. };
  48127. /**
  48128. * Returns the ShadowLight absolute position in the World.
  48129. * @returns the position vector in world space
  48130. */
  48131. ShadowLight.prototype.getAbsolutePosition = function () {
  48132. return this.transformedPosition ? this.transformedPosition : this.position;
  48133. };
  48134. /**
  48135. * Sets the ShadowLight direction toward the passed target.
  48136. * @param target The point tot target in local space
  48137. * @returns the updated ShadowLight direction
  48138. */
  48139. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48140. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48141. return this.direction;
  48142. };
  48143. /**
  48144. * Returns the light rotation in euler definition.
  48145. * @returns the x y z rotation in local space.
  48146. */
  48147. ShadowLight.prototype.getRotation = function () {
  48148. this.direction.normalize();
  48149. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48150. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48151. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48152. };
  48153. /**
  48154. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48155. * @returns true if a cube texture needs to be use
  48156. */
  48157. ShadowLight.prototype.needCube = function () {
  48158. return false;
  48159. };
  48160. /**
  48161. * Detects if the projection matrix requires to be recomputed this frame.
  48162. * @returns true if it requires to be recomputed otherwise, false.
  48163. */
  48164. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48165. return this._needProjectionMatrixCompute;
  48166. };
  48167. /**
  48168. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48169. */
  48170. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48171. this._needProjectionMatrixCompute = true;
  48172. };
  48173. /**
  48174. * Get the world matrix of the sahdow lights.
  48175. * @ignore Internal Use Only
  48176. */
  48177. ShadowLight.prototype._getWorldMatrix = function () {
  48178. if (!this._worldMatrix) {
  48179. this._worldMatrix = BABYLON.Matrix.Identity();
  48180. }
  48181. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48182. return this._worldMatrix;
  48183. };
  48184. /**
  48185. * Gets the minZ used for shadow according to both the scene and the light.
  48186. * @param activeCamera The camera we are returning the min for
  48187. * @returns the depth min z
  48188. */
  48189. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48190. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48191. };
  48192. /**
  48193. * Gets the maxZ used for shadow according to both the scene and the light.
  48194. * @param activeCamera The camera we are returning the max for
  48195. * @returns the depth max z
  48196. */
  48197. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48198. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48199. };
  48200. /**
  48201. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48202. * @param matrix The materix to updated with the projection information
  48203. * @param viewMatrix The transform matrix of the light
  48204. * @param renderList The list of mesh to render in the map
  48205. * @returns The current light
  48206. */
  48207. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48208. if (this.customProjectionMatrixBuilder) {
  48209. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48210. }
  48211. else {
  48212. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48213. }
  48214. return this;
  48215. };
  48216. __decorate([
  48217. BABYLON.serializeAsVector3()
  48218. ], ShadowLight.prototype, "position", null);
  48219. __decorate([
  48220. BABYLON.serializeAsVector3()
  48221. ], ShadowLight.prototype, "direction", null);
  48222. __decorate([
  48223. BABYLON.serialize()
  48224. ], ShadowLight.prototype, "shadowMinZ", null);
  48225. __decorate([
  48226. BABYLON.serialize()
  48227. ], ShadowLight.prototype, "shadowMaxZ", null);
  48228. return ShadowLight;
  48229. }(BABYLON.Light));
  48230. BABYLON.ShadowLight = ShadowLight;
  48231. })(BABYLON || (BABYLON = {}));
  48232. //# sourceMappingURL=babylon.shadowLight.js.map
  48233. "use strict";
  48234. var BABYLON;
  48235. (function (BABYLON) {
  48236. /**
  48237. * A point light is a light defined by an unique point in world space.
  48238. * The light is emitted in every direction from this point.
  48239. * A good example of a point light is a standard light bulb.
  48240. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48241. */
  48242. var PointLight = /** @class */ (function (_super) {
  48243. __extends(PointLight, _super);
  48244. /**
  48245. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48246. * A PointLight emits the light in every direction.
  48247. * It can cast shadows.
  48248. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48249. * ```javascript
  48250. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48251. * ```
  48252. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48253. * @param name The light friendly name
  48254. * @param position The position of the point light in the scene
  48255. * @param scene The scene the lights belongs to
  48256. */
  48257. function PointLight(name, position, scene) {
  48258. var _this = _super.call(this, name, scene) || this;
  48259. _this._shadowAngle = Math.PI / 2;
  48260. _this.position = position;
  48261. return _this;
  48262. }
  48263. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  48264. /**
  48265. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48266. * This specifies what angle the shadow will use to be created.
  48267. *
  48268. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48269. */
  48270. get: function () {
  48271. return this._shadowAngle;
  48272. },
  48273. /**
  48274. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48275. * This specifies what angle the shadow will use to be created.
  48276. *
  48277. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48278. */
  48279. set: function (value) {
  48280. this._shadowAngle = value;
  48281. this.forceProjectionMatrixCompute();
  48282. },
  48283. enumerable: true,
  48284. configurable: true
  48285. });
  48286. Object.defineProperty(PointLight.prototype, "direction", {
  48287. /**
  48288. * Gets the direction if it has been set.
  48289. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48290. */
  48291. get: function () {
  48292. return this._direction;
  48293. },
  48294. /**
  48295. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48296. */
  48297. set: function (value) {
  48298. var previousNeedCube = this.needCube();
  48299. this._direction = value;
  48300. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  48301. this._shadowGenerator.recreateShadowMap();
  48302. }
  48303. },
  48304. enumerable: true,
  48305. configurable: true
  48306. });
  48307. /**
  48308. * Returns the string "PointLight"
  48309. * @returns the class name
  48310. */
  48311. PointLight.prototype.getClassName = function () {
  48312. return "PointLight";
  48313. };
  48314. /**
  48315. * Returns the integer 0.
  48316. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48317. */
  48318. PointLight.prototype.getTypeID = function () {
  48319. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  48320. };
  48321. /**
  48322. * Specifies wether or not the shadowmap should be a cube texture.
  48323. * @returns true if the shadowmap needs to be a cube texture.
  48324. */
  48325. PointLight.prototype.needCube = function () {
  48326. return !this.direction;
  48327. };
  48328. /**
  48329. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  48330. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48331. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48332. */
  48333. PointLight.prototype.getShadowDirection = function (faceIndex) {
  48334. if (this.direction) {
  48335. return _super.prototype.getShadowDirection.call(this, faceIndex);
  48336. }
  48337. else {
  48338. switch (faceIndex) {
  48339. case 0:
  48340. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  48341. case 1:
  48342. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  48343. case 2:
  48344. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  48345. case 3:
  48346. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  48347. case 4:
  48348. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  48349. case 5:
  48350. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  48351. }
  48352. }
  48353. return BABYLON.Vector3.Zero();
  48354. };
  48355. /**
  48356. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  48357. * - fov = PI / 2
  48358. * - aspect ratio : 1.0
  48359. * - z-near and far equal to the active camera minZ and maxZ.
  48360. * Returns the PointLight.
  48361. */
  48362. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48363. var activeCamera = this.getScene().activeCamera;
  48364. if (!activeCamera) {
  48365. return;
  48366. }
  48367. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48368. };
  48369. PointLight.prototype._buildUniformLayout = function () {
  48370. this._uniformBuffer.addUniform("vLightData", 4);
  48371. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48372. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48373. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48374. this._uniformBuffer.addUniform("depthValues", 2);
  48375. this._uniformBuffer.create();
  48376. };
  48377. /**
  48378. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  48379. * @param effect The effect to update
  48380. * @param lightIndex The index of the light in the effect to update
  48381. * @returns The point light
  48382. */
  48383. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  48384. if (this.computeTransformedInformation()) {
  48385. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  48386. return this;
  48387. }
  48388. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  48389. return this;
  48390. };
  48391. __decorate([
  48392. BABYLON.serialize()
  48393. ], PointLight.prototype, "shadowAngle", null);
  48394. return PointLight;
  48395. }(BABYLON.ShadowLight));
  48396. BABYLON.PointLight = PointLight;
  48397. })(BABYLON || (BABYLON = {}));
  48398. //# sourceMappingURL=babylon.pointLight.js.map
  48399. "use strict";
  48400. var BABYLON;
  48401. (function (BABYLON) {
  48402. /**
  48403. * A directional light is defined by a direction (what a surprise!).
  48404. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  48405. * 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.
  48406. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48407. */
  48408. var DirectionalLight = /** @class */ (function (_super) {
  48409. __extends(DirectionalLight, _super);
  48410. /**
  48411. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  48412. * The directional light is emitted from everywhere in the given direction.
  48413. * It can cast shawdows.
  48414. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48415. * @param name The friendly name of the light
  48416. * @param direction The direction of the light
  48417. * @param scene The scene the light belongs to
  48418. */
  48419. function DirectionalLight(name, direction, scene) {
  48420. var _this = _super.call(this, name, scene) || this;
  48421. _this._shadowFrustumSize = 0;
  48422. _this._shadowOrthoScale = 0.1;
  48423. /**
  48424. * Automatically compute the projection matrix to best fit (including all the casters)
  48425. * on each frame.
  48426. */
  48427. _this.autoUpdateExtends = true;
  48428. // Cache
  48429. _this._orthoLeft = Number.MAX_VALUE;
  48430. _this._orthoRight = Number.MIN_VALUE;
  48431. _this._orthoTop = Number.MIN_VALUE;
  48432. _this._orthoBottom = Number.MAX_VALUE;
  48433. _this.position = direction.scale(-1.0);
  48434. _this.direction = direction;
  48435. return _this;
  48436. }
  48437. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  48438. /**
  48439. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  48440. */
  48441. get: function () {
  48442. return this._shadowFrustumSize;
  48443. },
  48444. /**
  48445. * Specifies a fix frustum size for the shadow generation.
  48446. */
  48447. set: function (value) {
  48448. this._shadowFrustumSize = value;
  48449. this.forceProjectionMatrixCompute();
  48450. },
  48451. enumerable: true,
  48452. configurable: true
  48453. });
  48454. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  48455. /**
  48456. * Gets the shadow projection scale against the optimal computed one.
  48457. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48458. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48459. */
  48460. get: function () {
  48461. return this._shadowOrthoScale;
  48462. },
  48463. /**
  48464. * Sets the shadow projection scale against the optimal computed one.
  48465. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48466. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48467. */
  48468. set: function (value) {
  48469. this._shadowOrthoScale = value;
  48470. this.forceProjectionMatrixCompute();
  48471. },
  48472. enumerable: true,
  48473. configurable: true
  48474. });
  48475. /**
  48476. * Returns the string "DirectionalLight".
  48477. * @return The class name
  48478. */
  48479. DirectionalLight.prototype.getClassName = function () {
  48480. return "DirectionalLight";
  48481. };
  48482. /**
  48483. * Returns the integer 1.
  48484. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48485. */
  48486. DirectionalLight.prototype.getTypeID = function () {
  48487. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  48488. };
  48489. /**
  48490. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  48491. * Returns the DirectionalLight Shadow projection matrix.
  48492. */
  48493. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48494. if (this.shadowFrustumSize > 0) {
  48495. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  48496. }
  48497. else {
  48498. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48499. }
  48500. };
  48501. /**
  48502. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  48503. * Returns the DirectionalLight Shadow projection matrix.
  48504. */
  48505. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  48506. var activeCamera = this.getScene().activeCamera;
  48507. if (!activeCamera) {
  48508. return;
  48509. }
  48510. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  48511. };
  48512. /**
  48513. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  48514. * Returns the DirectionalLight Shadow projection matrix.
  48515. */
  48516. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48517. var activeCamera = this.getScene().activeCamera;
  48518. if (!activeCamera) {
  48519. return;
  48520. }
  48521. // Check extends
  48522. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  48523. var tempVector3 = BABYLON.Vector3.Zero();
  48524. this._orthoLeft = Number.MAX_VALUE;
  48525. this._orthoRight = Number.MIN_VALUE;
  48526. this._orthoTop = Number.MIN_VALUE;
  48527. this._orthoBottom = Number.MAX_VALUE;
  48528. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  48529. var mesh = renderList[meshIndex];
  48530. if (!mesh) {
  48531. continue;
  48532. }
  48533. var boundingInfo = mesh.getBoundingInfo();
  48534. var boundingBox = boundingInfo.boundingBox;
  48535. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  48536. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  48537. if (tempVector3.x < this._orthoLeft)
  48538. this._orthoLeft = tempVector3.x;
  48539. if (tempVector3.y < this._orthoBottom)
  48540. this._orthoBottom = tempVector3.y;
  48541. if (tempVector3.x > this._orthoRight)
  48542. this._orthoRight = tempVector3.x;
  48543. if (tempVector3.y > this._orthoTop)
  48544. this._orthoTop = tempVector3.y;
  48545. }
  48546. }
  48547. }
  48548. var xOffset = this._orthoRight - this._orthoLeft;
  48549. var yOffset = this._orthoTop - this._orthoBottom;
  48550. 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);
  48551. };
  48552. DirectionalLight.prototype._buildUniformLayout = function () {
  48553. this._uniformBuffer.addUniform("vLightData", 4);
  48554. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48555. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48556. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48557. this._uniformBuffer.addUniform("depthValues", 2);
  48558. this._uniformBuffer.create();
  48559. };
  48560. /**
  48561. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  48562. * @param effect The effect to update
  48563. * @param lightIndex The index of the light in the effect to update
  48564. * @returns The directional light
  48565. */
  48566. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  48567. if (this.computeTransformedInformation()) {
  48568. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  48569. return this;
  48570. }
  48571. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  48572. return this;
  48573. };
  48574. /**
  48575. * Gets the minZ used for shadow according to both the scene and the light.
  48576. *
  48577. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48578. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48579. * @param activeCamera The camera we are returning the min for
  48580. * @returns the depth min z
  48581. */
  48582. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  48583. return 1;
  48584. };
  48585. /**
  48586. * Gets the maxZ used for shadow according to both the scene and the light.
  48587. *
  48588. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48589. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48590. * @param activeCamera The camera we are returning the max for
  48591. * @returns the depth max z
  48592. */
  48593. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  48594. return 1;
  48595. };
  48596. __decorate([
  48597. BABYLON.serialize()
  48598. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  48599. __decorate([
  48600. BABYLON.serialize()
  48601. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  48602. __decorate([
  48603. BABYLON.serialize()
  48604. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  48605. return DirectionalLight;
  48606. }(BABYLON.ShadowLight));
  48607. BABYLON.DirectionalLight = DirectionalLight;
  48608. })(BABYLON || (BABYLON = {}));
  48609. //# sourceMappingURL=babylon.directionalLight.js.map
  48610. "use strict";
  48611. var BABYLON;
  48612. (function (BABYLON) {
  48613. /**
  48614. * A spot light is defined by a position, a direction, an angle, and an exponent.
  48615. * These values define a cone of light starting from the position, emitting toward the direction.
  48616. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  48617. * and the exponent defines the speed of the decay of the light with distance (reach).
  48618. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48619. */
  48620. var SpotLight = /** @class */ (function (_super) {
  48621. __extends(SpotLight, _super);
  48622. /**
  48623. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  48624. * It can cast shadows.
  48625. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48626. * @param name The light friendly name
  48627. * @param position The position of the spot light in the scene
  48628. * @param direction The direction of the light in the scene
  48629. * @param angle The cone angle of the light in Radians
  48630. * @param exponent The light decay speed with the distance from the emission spot
  48631. * @param scene The scene the lights belongs to
  48632. */
  48633. function SpotLight(name, position, direction, angle, exponent, scene) {
  48634. var _this = _super.call(this, name, scene) || this;
  48635. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  48636. _this._projectionTextureLightNear = 1e-6;
  48637. _this._projectionTextureLightFar = 1000.0;
  48638. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  48639. _this._projectionTextureViewLightDirty = true;
  48640. _this._projectionTextureProjectionLightDirty = true;
  48641. _this._projectionTextureDirty = true;
  48642. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  48643. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  48644. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  48645. _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);
  48646. _this.position = position;
  48647. _this.direction = direction;
  48648. _this.angle = angle;
  48649. _this.exponent = exponent;
  48650. return _this;
  48651. }
  48652. Object.defineProperty(SpotLight.prototype, "angle", {
  48653. /**
  48654. * Gets the cone angle of the spot light in Radians.
  48655. */
  48656. get: function () {
  48657. return this._angle;
  48658. },
  48659. /**
  48660. * Sets the cone angle of the spot light in Radians.
  48661. */
  48662. set: function (value) {
  48663. this._angle = value;
  48664. this._projectionTextureProjectionLightDirty = true;
  48665. this.forceProjectionMatrixCompute();
  48666. },
  48667. enumerable: true,
  48668. configurable: true
  48669. });
  48670. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  48671. /**
  48672. * Allows scaling the angle of the light for shadow generation only.
  48673. */
  48674. get: function () {
  48675. return this._shadowAngleScale;
  48676. },
  48677. /**
  48678. * Allows scaling the angle of the light for shadow generation only.
  48679. */
  48680. set: function (value) {
  48681. this._shadowAngleScale = value;
  48682. this.forceProjectionMatrixCompute();
  48683. },
  48684. enumerable: true,
  48685. configurable: true
  48686. });
  48687. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  48688. /**
  48689. * Allows reading the projecton texture
  48690. */
  48691. get: function () {
  48692. return this._projectionTextureMatrix;
  48693. },
  48694. enumerable: true,
  48695. configurable: true
  48696. });
  48697. ;
  48698. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  48699. /**
  48700. * Gets the near clip of the Spotlight for texture projection.
  48701. */
  48702. get: function () {
  48703. return this._projectionTextureLightNear;
  48704. },
  48705. /**
  48706. * Sets the near clip of the Spotlight for texture projection.
  48707. */
  48708. set: function (value) {
  48709. this._projectionTextureLightNear = value;
  48710. this._projectionTextureProjectionLightDirty = true;
  48711. },
  48712. enumerable: true,
  48713. configurable: true
  48714. });
  48715. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  48716. /**
  48717. * Gets the far clip of the Spotlight for texture projection.
  48718. */
  48719. get: function () {
  48720. return this._projectionTextureLightFar;
  48721. },
  48722. /**
  48723. * Sets the far clip of the Spotlight for texture projection.
  48724. */
  48725. set: function (value) {
  48726. this._projectionTextureLightFar = value;
  48727. this._projectionTextureProjectionLightDirty = true;
  48728. },
  48729. enumerable: true,
  48730. configurable: true
  48731. });
  48732. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  48733. /**
  48734. * Gets the Up vector of the Spotlight for texture projection.
  48735. */
  48736. get: function () {
  48737. return this._projectionTextureUpDirection;
  48738. },
  48739. /**
  48740. * Sets the Up vector of the Spotlight for texture projection.
  48741. */
  48742. set: function (value) {
  48743. this._projectionTextureUpDirection = value;
  48744. this._projectionTextureProjectionLightDirty = true;
  48745. },
  48746. enumerable: true,
  48747. configurable: true
  48748. });
  48749. ;
  48750. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  48751. /**
  48752. * Gets the projection texture of the light.
  48753. */
  48754. get: function () {
  48755. return this._projectionTexture;
  48756. },
  48757. /**
  48758. * Sets the projection texture of the light.
  48759. */
  48760. set: function (value) {
  48761. this._projectionTexture = value;
  48762. this._projectionTextureDirty = true;
  48763. },
  48764. enumerable: true,
  48765. configurable: true
  48766. });
  48767. /**
  48768. * Returns the string "SpotLight".
  48769. * @returns the class name
  48770. */
  48771. SpotLight.prototype.getClassName = function () {
  48772. return "SpotLight";
  48773. };
  48774. /**
  48775. * Returns the integer 2.
  48776. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48777. */
  48778. SpotLight.prototype.getTypeID = function () {
  48779. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  48780. };
  48781. /**
  48782. * Overrides the direction setter to recompute the projection texture view light Matrix.
  48783. */
  48784. SpotLight.prototype._setDirection = function (value) {
  48785. _super.prototype._setDirection.call(this, value);
  48786. this._projectionTextureViewLightDirty = true;
  48787. };
  48788. /**
  48789. * Overrides the position setter to recompute the projection texture view light Matrix.
  48790. */
  48791. SpotLight.prototype._setPosition = function (value) {
  48792. _super.prototype._setPosition.call(this, value);
  48793. this._projectionTextureViewLightDirty = true;
  48794. };
  48795. /**
  48796. * 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.
  48797. * Returns the SpotLight.
  48798. */
  48799. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48800. var activeCamera = this.getScene().activeCamera;
  48801. if (!activeCamera) {
  48802. return;
  48803. }
  48804. this._shadowAngleScale = this._shadowAngleScale || 1;
  48805. var angle = this._shadowAngleScale * this._angle;
  48806. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48807. };
  48808. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  48809. this._projectionTextureViewLightDirty = false;
  48810. this._projectionTextureDirty = true;
  48811. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  48812. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  48813. };
  48814. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  48815. this._projectionTextureProjectionLightDirty = false;
  48816. this._projectionTextureDirty = true;
  48817. var light_far = this.projectionTextureLightFar;
  48818. var light_near = this.projectionTextureLightNear;
  48819. var P = light_far / (light_far - light_near);
  48820. var Q = -P * light_near;
  48821. var S = 1.0 / Math.tan(this._angle / 2.0);
  48822. var A = 1.0;
  48823. 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);
  48824. };
  48825. /**
  48826. * Main function for light texture projection matrix computing.
  48827. */
  48828. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  48829. this._projectionTextureDirty = false;
  48830. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  48831. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  48832. };
  48833. SpotLight.prototype._buildUniformLayout = function () {
  48834. this._uniformBuffer.addUniform("vLightData", 4);
  48835. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48836. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48837. this._uniformBuffer.addUniform("vLightDirection", 3);
  48838. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48839. this._uniformBuffer.addUniform("depthValues", 2);
  48840. this._uniformBuffer.create();
  48841. };
  48842. /**
  48843. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  48844. * @param effect The effect to update
  48845. * @param lightIndex The index of the light in the effect to update
  48846. * @returns The spot light
  48847. */
  48848. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  48849. var normalizeDirection;
  48850. if (this.computeTransformedInformation()) {
  48851. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  48852. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  48853. }
  48854. else {
  48855. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  48856. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48857. }
  48858. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  48859. if (this.projectionTexture && this.projectionTexture.isReady()) {
  48860. if (this._projectionTextureViewLightDirty) {
  48861. this._computeProjectionTextureViewLightMatrix();
  48862. }
  48863. if (this._projectionTextureProjectionLightDirty) {
  48864. this._computeProjectionTextureProjectionLightMatrix();
  48865. }
  48866. if (this._projectionTextureDirty) {
  48867. this._computeProjectionTextureMatrix();
  48868. }
  48869. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  48870. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  48871. }
  48872. return this;
  48873. };
  48874. /**
  48875. * Disposes the light and the associated resources.
  48876. */
  48877. SpotLight.prototype.dispose = function () {
  48878. _super.prototype.dispose.call(this);
  48879. if (this._projectionTexture) {
  48880. this._projectionTexture.dispose();
  48881. }
  48882. };
  48883. __decorate([
  48884. BABYLON.serialize()
  48885. ], SpotLight.prototype, "angle", null);
  48886. __decorate([
  48887. BABYLON.serialize()
  48888. ], SpotLight.prototype, "shadowAngleScale", null);
  48889. __decorate([
  48890. BABYLON.serialize()
  48891. ], SpotLight.prototype, "exponent", void 0);
  48892. __decorate([
  48893. BABYLON.serialize()
  48894. ], SpotLight.prototype, "projectionTextureLightNear", null);
  48895. __decorate([
  48896. BABYLON.serialize()
  48897. ], SpotLight.prototype, "projectionTextureLightFar", null);
  48898. __decorate([
  48899. BABYLON.serialize()
  48900. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  48901. __decorate([
  48902. BABYLON.serializeAsTexture("projectedLightTexture")
  48903. ], SpotLight.prototype, "_projectionTexture", void 0);
  48904. return SpotLight;
  48905. }(BABYLON.ShadowLight));
  48906. BABYLON.SpotLight = SpotLight;
  48907. })(BABYLON || (BABYLON = {}));
  48908. //# sourceMappingURL=babylon.spotLight.js.map
  48909. "use strict";
  48910. var BABYLON;
  48911. (function (BABYLON) {
  48912. /**
  48913. * Class used to override all child animations of a given target
  48914. */
  48915. var AnimationPropertiesOverride = /** @class */ (function () {
  48916. function AnimationPropertiesOverride() {
  48917. /**
  48918. * Gets or sets a value indicating if animation blending must be used
  48919. */
  48920. this.enableBlending = false;
  48921. /**
  48922. * Gets or sets the blending speed to use when enableBlending is true
  48923. */
  48924. this.blendingSpeed = 0.01;
  48925. /**
  48926. * Gets or sets the default loop mode to use
  48927. */
  48928. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  48929. }
  48930. return AnimationPropertiesOverride;
  48931. }());
  48932. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  48933. })(BABYLON || (BABYLON = {}));
  48934. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  48935. "use strict";
  48936. var BABYLON;
  48937. (function (BABYLON) {
  48938. var AnimationRange = /** @class */ (function () {
  48939. function AnimationRange(name, from, to) {
  48940. this.name = name;
  48941. this.from = from;
  48942. this.to = to;
  48943. }
  48944. AnimationRange.prototype.clone = function () {
  48945. return new AnimationRange(this.name, this.from, this.to);
  48946. };
  48947. return AnimationRange;
  48948. }());
  48949. BABYLON.AnimationRange = AnimationRange;
  48950. /**
  48951. * Composed of a frame, and an action function
  48952. */
  48953. var AnimationEvent = /** @class */ (function () {
  48954. function AnimationEvent(frame, action, onlyOnce) {
  48955. this.frame = frame;
  48956. this.action = action;
  48957. this.onlyOnce = onlyOnce;
  48958. this.isDone = false;
  48959. }
  48960. return AnimationEvent;
  48961. }());
  48962. BABYLON.AnimationEvent = AnimationEvent;
  48963. var PathCursor = /** @class */ (function () {
  48964. function PathCursor(path) {
  48965. this.path = path;
  48966. this._onchange = new Array();
  48967. this.value = 0;
  48968. this.animations = new Array();
  48969. }
  48970. PathCursor.prototype.getPoint = function () {
  48971. var point = this.path.getPointAtLengthPosition(this.value);
  48972. return new BABYLON.Vector3(point.x, 0, point.y);
  48973. };
  48974. PathCursor.prototype.moveAhead = function (step) {
  48975. if (step === void 0) { step = 0.002; }
  48976. this.move(step);
  48977. return this;
  48978. };
  48979. PathCursor.prototype.moveBack = function (step) {
  48980. if (step === void 0) { step = 0.002; }
  48981. this.move(-step);
  48982. return this;
  48983. };
  48984. PathCursor.prototype.move = function (step) {
  48985. if (Math.abs(step) > 1) {
  48986. throw "step size should be less than 1.";
  48987. }
  48988. this.value += step;
  48989. this.ensureLimits();
  48990. this.raiseOnChange();
  48991. return this;
  48992. };
  48993. PathCursor.prototype.ensureLimits = function () {
  48994. while (this.value > 1) {
  48995. this.value -= 1;
  48996. }
  48997. while (this.value < 0) {
  48998. this.value += 1;
  48999. }
  49000. return this;
  49001. };
  49002. // used by animation engine
  49003. PathCursor.prototype.raiseOnChange = function () {
  49004. var _this = this;
  49005. this._onchange.forEach(function (f) { return f(_this); });
  49006. return this;
  49007. };
  49008. PathCursor.prototype.onchange = function (f) {
  49009. this._onchange.push(f);
  49010. return this;
  49011. };
  49012. return PathCursor;
  49013. }());
  49014. BABYLON.PathCursor = PathCursor;
  49015. var AnimationKeyInterpolation;
  49016. (function (AnimationKeyInterpolation) {
  49017. /**
  49018. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  49019. */
  49020. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49021. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49022. var Animation = /** @class */ (function () {
  49023. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  49024. this.name = name;
  49025. this.targetProperty = targetProperty;
  49026. this.framePerSecond = framePerSecond;
  49027. this.dataType = dataType;
  49028. this.loopMode = loopMode;
  49029. this.enableBlending = enableBlending;
  49030. this._runtimeAnimations = new Array();
  49031. // The set of event that will be linked to this animation
  49032. this._events = new Array();
  49033. this.blendingSpeed = 0.01;
  49034. this._ranges = {};
  49035. this.targetPropertyPath = targetProperty.split(".");
  49036. this.dataType = dataType;
  49037. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49038. }
  49039. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49040. var dataType = undefined;
  49041. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49042. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49043. }
  49044. else if (from instanceof BABYLON.Quaternion) {
  49045. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49046. }
  49047. else if (from instanceof BABYLON.Vector3) {
  49048. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49049. }
  49050. else if (from instanceof BABYLON.Vector2) {
  49051. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49052. }
  49053. else if (from instanceof BABYLON.Color3) {
  49054. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49055. }
  49056. else if (from instanceof BABYLON.Size) {
  49057. dataType = Animation.ANIMATIONTYPE_SIZE;
  49058. }
  49059. if (dataType == undefined) {
  49060. return null;
  49061. }
  49062. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49063. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49064. animation.setKeys(keys);
  49065. if (easingFunction !== undefined) {
  49066. animation.setEasingFunction(easingFunction);
  49067. }
  49068. return animation;
  49069. };
  49070. /**
  49071. * Sets up an animation.
  49072. * @param property the property to animate
  49073. * @param animationType the animation type to apply
  49074. * @param easingFunction the easing function used in the animation
  49075. * @returns The created animation
  49076. */
  49077. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49078. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49079. animation.setEasingFunction(easingFunction);
  49080. return animation;
  49081. };
  49082. /**
  49083. * Create and start an animation on a node
  49084. * @param {string} name defines the name of the global animation that will be run on all nodes
  49085. * @param {BABYLON.Node} node defines the root node where the animation will take place
  49086. * @param {string} targetProperty defines property to animate
  49087. * @param {number} framePerSecond defines the number of frame per second yo use
  49088. * @param {number} totalFrame defines the number of frames in total
  49089. * @param {any} from defines the initial value
  49090. * @param {any} to defines the final value
  49091. * @param {number} loopMode defines which loop mode you want to use (off by default)
  49092. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  49093. * @param onAnimationEnd defines the callback to call when animation end
  49094. * @returns the animatable created for this animation
  49095. */
  49096. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49097. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49098. if (!animation) {
  49099. return null;
  49100. }
  49101. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49102. };
  49103. /**
  49104. * Create and start an animation on a node and its descendants
  49105. * @param {string} name defines the name of the global animation that will be run on all nodes
  49106. * @param {BABYLON.Node} node defines the root node where the animation will take place
  49107. * @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.
  49108. * @param {string} targetProperty defines property to animate
  49109. * @param {number} framePerSecond defines the number of frame per second yo use
  49110. * @param {number} totalFrame defines the number of frames in total
  49111. * @param {any} from defines the initial value
  49112. * @param {any} to defines the final value
  49113. * @param {number} loopMode defines which loop mode you want to use (off by default)
  49114. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  49115. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49116. * @returns the list of animatables created for all nodes
  49117. * @example https://www.babylonjs-playground.com/#MH0VLI
  49118. */
  49119. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49120. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49121. if (!animation) {
  49122. return null;
  49123. }
  49124. var scene = node.getScene();
  49125. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49126. };
  49127. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49128. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49129. if (!animation) {
  49130. return null;
  49131. }
  49132. node.animations.push(animation);
  49133. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49134. };
  49135. /**
  49136. * Transition property of the Camera to the target Value.
  49137. * @param property The property to transition
  49138. * @param targetValue The target Value of the property
  49139. * @param host The object where the property to animate belongs
  49140. * @param scene Scene used to run the animation
  49141. * @param frameRate Framerate (in frame/s) to use
  49142. * @param transition The transition type we want to use
  49143. * @param duration The duration of the animation, in milliseconds
  49144. * @param onAnimationEnd Call back trigger at the end of the animation.
  49145. */
  49146. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49147. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49148. if (duration <= 0) {
  49149. host[property] = targetValue;
  49150. if (onAnimationEnd) {
  49151. onAnimationEnd();
  49152. }
  49153. return null;
  49154. }
  49155. var endFrame = frameRate * (duration / 1000);
  49156. transition.setKeys([{
  49157. frame: 0,
  49158. value: host[property].clone ? host[property].clone() : host[property]
  49159. },
  49160. {
  49161. frame: endFrame,
  49162. value: targetValue
  49163. }]);
  49164. if (!host.animations) {
  49165. host.animations = [];
  49166. }
  49167. host.animations.push(transition);
  49168. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49169. animation.onAnimationEnd = onAnimationEnd;
  49170. return animation;
  49171. };
  49172. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49173. /**
  49174. * Return the array of runtime animations currently using this animation
  49175. */
  49176. get: function () {
  49177. return this._runtimeAnimations;
  49178. },
  49179. enumerable: true,
  49180. configurable: true
  49181. });
  49182. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  49183. get: function () {
  49184. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  49185. var runtimeAnimation = _a[_i];
  49186. if (!runtimeAnimation.isStopped) {
  49187. return true;
  49188. }
  49189. }
  49190. return false;
  49191. },
  49192. enumerable: true,
  49193. configurable: true
  49194. });
  49195. // Methods
  49196. /**
  49197. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  49198. */
  49199. Animation.prototype.toString = function (fullDetails) {
  49200. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  49201. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  49202. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  49203. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  49204. if (fullDetails) {
  49205. ret += ", Ranges: {";
  49206. var first = true;
  49207. for (var name in this._ranges) {
  49208. if (first) {
  49209. ret += ", ";
  49210. first = false;
  49211. }
  49212. ret += name;
  49213. }
  49214. ret += "}";
  49215. }
  49216. return ret;
  49217. };
  49218. /**
  49219. * Add an event to this animation.
  49220. */
  49221. Animation.prototype.addEvent = function (event) {
  49222. this._events.push(event);
  49223. };
  49224. /**
  49225. * Remove all events found at the given frame
  49226. * @param frame
  49227. */
  49228. Animation.prototype.removeEvents = function (frame) {
  49229. for (var index = 0; index < this._events.length; index++) {
  49230. if (this._events[index].frame === frame) {
  49231. this._events.splice(index, 1);
  49232. index--;
  49233. }
  49234. }
  49235. };
  49236. Animation.prototype.getEvents = function () {
  49237. return this._events;
  49238. };
  49239. Animation.prototype.createRange = function (name, from, to) {
  49240. // check name not already in use; could happen for bones after serialized
  49241. if (!this._ranges[name]) {
  49242. this._ranges[name] = new AnimationRange(name, from, to);
  49243. }
  49244. };
  49245. Animation.prototype.deleteRange = function (name, deleteFrames) {
  49246. if (deleteFrames === void 0) { deleteFrames = true; }
  49247. var range = this._ranges[name];
  49248. if (!range) {
  49249. return;
  49250. }
  49251. if (deleteFrames) {
  49252. var from = range.from;
  49253. var to = range.to;
  49254. // this loop MUST go high to low for multiple splices to work
  49255. for (var key = this._keys.length - 1; key >= 0; key--) {
  49256. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  49257. this._keys.splice(key, 1);
  49258. }
  49259. }
  49260. }
  49261. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  49262. };
  49263. Animation.prototype.getRange = function (name) {
  49264. return this._ranges[name];
  49265. };
  49266. Animation.prototype.getKeys = function () {
  49267. return this._keys;
  49268. };
  49269. Animation.prototype.getHighestFrame = function () {
  49270. var ret = 0;
  49271. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  49272. if (ret < this._keys[key].frame) {
  49273. ret = this._keys[key].frame;
  49274. }
  49275. }
  49276. return ret;
  49277. };
  49278. Animation.prototype.getEasingFunction = function () {
  49279. return this._easingFunction;
  49280. };
  49281. Animation.prototype.setEasingFunction = function (easingFunction) {
  49282. this._easingFunction = easingFunction;
  49283. };
  49284. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  49285. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  49286. };
  49287. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49288. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49289. };
  49290. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  49291. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  49292. };
  49293. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49294. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  49295. };
  49296. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  49297. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  49298. };
  49299. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49300. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49301. };
  49302. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  49303. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  49304. };
  49305. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49306. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49307. };
  49308. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  49309. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  49310. };
  49311. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  49312. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  49313. };
  49314. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  49315. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  49316. };
  49317. Animation.prototype.clone = function () {
  49318. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  49319. clone.enableBlending = this.enableBlending;
  49320. clone.blendingSpeed = this.blendingSpeed;
  49321. if (this._keys) {
  49322. clone.setKeys(this._keys);
  49323. }
  49324. if (this._ranges) {
  49325. clone._ranges = {};
  49326. for (var name in this._ranges) {
  49327. var range = this._ranges[name];
  49328. if (!range) {
  49329. continue;
  49330. }
  49331. clone._ranges[name] = range.clone();
  49332. }
  49333. }
  49334. return clone;
  49335. };
  49336. Animation.prototype.setKeys = function (values) {
  49337. this._keys = values.slice(0);
  49338. };
  49339. Animation.prototype.serialize = function () {
  49340. var serializationObject = {};
  49341. serializationObject.name = this.name;
  49342. serializationObject.property = this.targetProperty;
  49343. serializationObject.framePerSecond = this.framePerSecond;
  49344. serializationObject.dataType = this.dataType;
  49345. serializationObject.loopBehavior = this.loopMode;
  49346. serializationObject.enableBlending = this.enableBlending;
  49347. serializationObject.blendingSpeed = this.blendingSpeed;
  49348. var dataType = this.dataType;
  49349. serializationObject.keys = [];
  49350. var keys = this.getKeys();
  49351. for (var index = 0; index < keys.length; index++) {
  49352. var animationKey = keys[index];
  49353. var key = {};
  49354. key.frame = animationKey.frame;
  49355. switch (dataType) {
  49356. case Animation.ANIMATIONTYPE_FLOAT:
  49357. key.values = [animationKey.value];
  49358. break;
  49359. case Animation.ANIMATIONTYPE_QUATERNION:
  49360. case Animation.ANIMATIONTYPE_MATRIX:
  49361. case Animation.ANIMATIONTYPE_VECTOR3:
  49362. case Animation.ANIMATIONTYPE_COLOR3:
  49363. key.values = animationKey.value.asArray();
  49364. break;
  49365. }
  49366. serializationObject.keys.push(key);
  49367. }
  49368. serializationObject.ranges = [];
  49369. for (var name in this._ranges) {
  49370. var source = this._ranges[name];
  49371. if (!source) {
  49372. continue;
  49373. }
  49374. var range = {};
  49375. range.name = name;
  49376. range.from = source.from;
  49377. range.to = source.to;
  49378. serializationObject.ranges.push(range);
  49379. }
  49380. return serializationObject;
  49381. };
  49382. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  49383. get: function () {
  49384. return Animation._ANIMATIONTYPE_FLOAT;
  49385. },
  49386. enumerable: true,
  49387. configurable: true
  49388. });
  49389. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  49390. get: function () {
  49391. return Animation._ANIMATIONTYPE_VECTOR3;
  49392. },
  49393. enumerable: true,
  49394. configurable: true
  49395. });
  49396. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  49397. get: function () {
  49398. return Animation._ANIMATIONTYPE_VECTOR2;
  49399. },
  49400. enumerable: true,
  49401. configurable: true
  49402. });
  49403. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  49404. get: function () {
  49405. return Animation._ANIMATIONTYPE_SIZE;
  49406. },
  49407. enumerable: true,
  49408. configurable: true
  49409. });
  49410. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  49411. get: function () {
  49412. return Animation._ANIMATIONTYPE_QUATERNION;
  49413. },
  49414. enumerable: true,
  49415. configurable: true
  49416. });
  49417. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  49418. get: function () {
  49419. return Animation._ANIMATIONTYPE_MATRIX;
  49420. },
  49421. enumerable: true,
  49422. configurable: true
  49423. });
  49424. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  49425. get: function () {
  49426. return Animation._ANIMATIONTYPE_COLOR3;
  49427. },
  49428. enumerable: true,
  49429. configurable: true
  49430. });
  49431. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  49432. get: function () {
  49433. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  49434. },
  49435. enumerable: true,
  49436. configurable: true
  49437. });
  49438. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  49439. get: function () {
  49440. return Animation._ANIMATIONLOOPMODE_CYCLE;
  49441. },
  49442. enumerable: true,
  49443. configurable: true
  49444. });
  49445. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  49446. get: function () {
  49447. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  49448. },
  49449. enumerable: true,
  49450. configurable: true
  49451. });
  49452. Animation.Parse = function (parsedAnimation) {
  49453. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  49454. var dataType = parsedAnimation.dataType;
  49455. var keys = [];
  49456. var data;
  49457. var index;
  49458. if (parsedAnimation.enableBlending) {
  49459. animation.enableBlending = parsedAnimation.enableBlending;
  49460. }
  49461. if (parsedAnimation.blendingSpeed) {
  49462. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  49463. }
  49464. for (index = 0; index < parsedAnimation.keys.length; index++) {
  49465. var key = parsedAnimation.keys[index];
  49466. var inTangent;
  49467. var outTangent;
  49468. switch (dataType) {
  49469. case Animation.ANIMATIONTYPE_FLOAT:
  49470. data = key.values[0];
  49471. if (key.values.length >= 1) {
  49472. inTangent = key.values[1];
  49473. }
  49474. if (key.values.length >= 2) {
  49475. outTangent = key.values[2];
  49476. }
  49477. break;
  49478. case Animation.ANIMATIONTYPE_QUATERNION:
  49479. data = BABYLON.Quaternion.FromArray(key.values);
  49480. if (key.values.length >= 8) {
  49481. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  49482. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  49483. inTangent = _inTangent;
  49484. }
  49485. }
  49486. if (key.values.length >= 12) {
  49487. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  49488. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  49489. outTangent = _outTangent;
  49490. }
  49491. }
  49492. break;
  49493. case Animation.ANIMATIONTYPE_MATRIX:
  49494. data = BABYLON.Matrix.FromArray(key.values);
  49495. break;
  49496. case Animation.ANIMATIONTYPE_COLOR3:
  49497. data = BABYLON.Color3.FromArray(key.values);
  49498. break;
  49499. case Animation.ANIMATIONTYPE_VECTOR3:
  49500. default:
  49501. data = BABYLON.Vector3.FromArray(key.values);
  49502. break;
  49503. }
  49504. var keyData = {};
  49505. keyData.frame = key.frame;
  49506. keyData.value = data;
  49507. if (inTangent != undefined) {
  49508. keyData.inTangent = inTangent;
  49509. }
  49510. if (outTangent != undefined) {
  49511. keyData.outTangent = outTangent;
  49512. }
  49513. keys.push(keyData);
  49514. }
  49515. animation.setKeys(keys);
  49516. if (parsedAnimation.ranges) {
  49517. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  49518. data = parsedAnimation.ranges[index];
  49519. animation.createRange(data.name, data.from, data.to);
  49520. }
  49521. }
  49522. return animation;
  49523. };
  49524. Animation.AppendSerializedAnimations = function (source, destination) {
  49525. if (source.animations) {
  49526. destination.animations = [];
  49527. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  49528. var animation = source.animations[animationIndex];
  49529. destination.animations.push(animation.serialize());
  49530. }
  49531. }
  49532. };
  49533. Animation.AllowMatricesInterpolation = false;
  49534. // Statics
  49535. Animation._ANIMATIONTYPE_FLOAT = 0;
  49536. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  49537. Animation._ANIMATIONTYPE_QUATERNION = 2;
  49538. Animation._ANIMATIONTYPE_MATRIX = 3;
  49539. Animation._ANIMATIONTYPE_COLOR3 = 4;
  49540. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  49541. Animation._ANIMATIONTYPE_SIZE = 6;
  49542. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  49543. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  49544. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  49545. return Animation;
  49546. }());
  49547. BABYLON.Animation = Animation;
  49548. })(BABYLON || (BABYLON = {}));
  49549. //# sourceMappingURL=babylon.animation.js.map
  49550. "use strict";
  49551. var BABYLON;
  49552. (function (BABYLON) {
  49553. /**
  49554. * This class defines the direct association between an animation and a target
  49555. */
  49556. var TargetedAnimation = /** @class */ (function () {
  49557. function TargetedAnimation() {
  49558. }
  49559. return TargetedAnimation;
  49560. }());
  49561. BABYLON.TargetedAnimation = TargetedAnimation;
  49562. /**
  49563. * Use this class to create coordinated animations on multiple targets
  49564. */
  49565. var AnimationGroup = /** @class */ (function () {
  49566. function AnimationGroup(name, scene) {
  49567. if (scene === void 0) { scene = null; }
  49568. this.name = name;
  49569. this._targetedAnimations = new Array();
  49570. this._animatables = new Array();
  49571. this._from = Number.MAX_VALUE;
  49572. this._to = -Number.MAX_VALUE;
  49573. this._speedRatio = 1;
  49574. this.onAnimationEndObservable = new BABYLON.Observable();
  49575. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  49576. this._scene.animationGroups.push(this);
  49577. }
  49578. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  49579. /**
  49580. * Define if the animations are started
  49581. */
  49582. get: function () {
  49583. return this._isStarted;
  49584. },
  49585. enumerable: true,
  49586. configurable: true
  49587. });
  49588. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  49589. /**
  49590. * Gets or sets the speed ratio to use for all animations
  49591. */
  49592. get: function () {
  49593. return this._speedRatio;
  49594. },
  49595. /**
  49596. * Gets or sets the speed ratio to use for all animations
  49597. */
  49598. set: function (value) {
  49599. if (this._speedRatio === value) {
  49600. return;
  49601. }
  49602. this._speedRatio = value;
  49603. for (var index = 0; index < this._animatables.length; index++) {
  49604. var animatable = this._animatables[index];
  49605. animatable.speedRatio = this._speedRatio;
  49606. }
  49607. },
  49608. enumerable: true,
  49609. configurable: true
  49610. });
  49611. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  49612. /**
  49613. * Gets the targeted animations for this animation group
  49614. */
  49615. get: function () {
  49616. return this._targetedAnimations;
  49617. },
  49618. enumerable: true,
  49619. configurable: true
  49620. });
  49621. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  49622. /**
  49623. * returning the list of animatables controlled by this animation group.
  49624. */
  49625. get: function () {
  49626. return this._animatables;
  49627. },
  49628. enumerable: true,
  49629. configurable: true
  49630. });
  49631. /**
  49632. * Add an animation (with its target) in the group
  49633. * @param animation defines the animation we want to add
  49634. * @param target defines the target of the animation
  49635. * @returns the {BABYLON.TargetedAnimation} object
  49636. */
  49637. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  49638. var targetedAnimation = {
  49639. animation: animation,
  49640. target: target
  49641. };
  49642. var keys = animation.getKeys();
  49643. if (this._from > keys[0].frame) {
  49644. this._from = keys[0].frame;
  49645. }
  49646. if (this._to < keys[keys.length - 1].frame) {
  49647. this._to = keys[keys.length - 1].frame;
  49648. }
  49649. this._targetedAnimations.push(targetedAnimation);
  49650. return targetedAnimation;
  49651. };
  49652. /**
  49653. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  49654. * It can add constant keys at begin or end
  49655. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  49656. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  49657. */
  49658. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  49659. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  49660. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  49661. beginFrame = Math.max(beginFrame, this._from);
  49662. endFrame = Math.min(endFrame, this._to);
  49663. for (var index = 0; index < this._targetedAnimations.length; index++) {
  49664. var targetedAnimation = this._targetedAnimations[index];
  49665. var keys = targetedAnimation.animation.getKeys();
  49666. var startKey = keys[0];
  49667. var endKey = keys[keys.length - 1];
  49668. if (startKey.frame > beginFrame) {
  49669. var newKey = {
  49670. frame: beginFrame,
  49671. value: startKey.value,
  49672. inTangent: startKey.inTangent,
  49673. outTangent: startKey.outTangent,
  49674. interpolation: startKey.interpolation
  49675. };
  49676. keys.splice(0, 0, newKey);
  49677. }
  49678. if (endKey.frame < endFrame) {
  49679. var newKey = {
  49680. frame: endFrame,
  49681. value: endKey.value,
  49682. inTangent: endKey.outTangent,
  49683. outTangent: endKey.outTangent,
  49684. interpolation: endKey.interpolation
  49685. };
  49686. keys.push(newKey);
  49687. }
  49688. }
  49689. return this;
  49690. };
  49691. /**
  49692. * Start all animations on given targets
  49693. * @param loop defines if animations must loop
  49694. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  49695. * @param from defines the from key (optional)
  49696. * @param to defines the to key (optional)
  49697. * @returns the current animation group
  49698. */
  49699. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  49700. var _this = this;
  49701. if (loop === void 0) { loop = false; }
  49702. if (speedRatio === void 0) { speedRatio = 1; }
  49703. if (this._isStarted || this._targetedAnimations.length === 0) {
  49704. return this;
  49705. }
  49706. var _loop_1 = function () {
  49707. var targetedAnimation = this_1._targetedAnimations[index];
  49708. if (!targetedAnimation.target.animations) {
  49709. targetedAnimation.target.animations = [];
  49710. }
  49711. if (targetedAnimation.target.animations.indexOf(targetedAnimation.animation) === -1) {
  49712. targetedAnimation.target.animations.push(targetedAnimation.animation);
  49713. }
  49714. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio, function () {
  49715. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  49716. }));
  49717. };
  49718. var this_1 = this;
  49719. for (var index = 0; index < this._targetedAnimations.length; index++) {
  49720. _loop_1();
  49721. }
  49722. this._speedRatio = speedRatio;
  49723. this._isStarted = true;
  49724. return this;
  49725. };
  49726. /**
  49727. * Pause all animations
  49728. */
  49729. AnimationGroup.prototype.pause = function () {
  49730. if (!this._isStarted) {
  49731. return this;
  49732. }
  49733. for (var index = 0; index < this._animatables.length; index++) {
  49734. var animatable = this._animatables[index];
  49735. animatable.pause();
  49736. }
  49737. return this;
  49738. };
  49739. /**
  49740. * Play all animations to initial state
  49741. * This function will start() the animations if they were not started or will restart() them if they were paused
  49742. * @param loop defines if animations must loop
  49743. */
  49744. AnimationGroup.prototype.play = function (loop) {
  49745. if (this.isStarted) {
  49746. if (loop !== undefined) {
  49747. for (var index = 0; index < this._animatables.length; index++) {
  49748. var animatable = this._animatables[index];
  49749. animatable.loopAnimation = loop;
  49750. }
  49751. }
  49752. this.restart();
  49753. }
  49754. else {
  49755. this.start(loop, this._speedRatio);
  49756. }
  49757. return this;
  49758. };
  49759. /**
  49760. * Reset all animations to initial state
  49761. */
  49762. AnimationGroup.prototype.reset = function () {
  49763. if (!this._isStarted) {
  49764. return this;
  49765. }
  49766. for (var index = 0; index < this._animatables.length; index++) {
  49767. var animatable = this._animatables[index];
  49768. animatable.reset();
  49769. }
  49770. return this;
  49771. };
  49772. /**
  49773. * Restart animations from key 0
  49774. */
  49775. AnimationGroup.prototype.restart = function () {
  49776. if (!this._isStarted) {
  49777. return this;
  49778. }
  49779. for (var index = 0; index < this._animatables.length; index++) {
  49780. var animatable = this._animatables[index];
  49781. animatable.restart();
  49782. }
  49783. return this;
  49784. };
  49785. /**
  49786. * Stop all animations
  49787. */
  49788. AnimationGroup.prototype.stop = function () {
  49789. if (!this._isStarted) {
  49790. return this;
  49791. }
  49792. for (var index = 0; index < this._animatables.length; index++) {
  49793. var animatable = this._animatables[index];
  49794. animatable.stop();
  49795. }
  49796. this._isStarted = false;
  49797. return this;
  49798. };
  49799. /**
  49800. * Goes to a specific frame in this animation group
  49801. *
  49802. * @param frame the frame number to go to
  49803. * @return the animationGroup
  49804. */
  49805. AnimationGroup.prototype.goToFrame = function (frame) {
  49806. if (!this._isStarted) {
  49807. return this;
  49808. }
  49809. for (var index = 0; index < this._animatables.length; index++) {
  49810. var animatable = this._animatables[index];
  49811. animatable.goToFrame(frame);
  49812. }
  49813. return this;
  49814. };
  49815. /**
  49816. * Dispose all associated resources
  49817. */
  49818. AnimationGroup.prototype.dispose = function () {
  49819. this._targetedAnimations = [];
  49820. this._animatables = [];
  49821. var index = this._scene.animationGroups.indexOf(this);
  49822. if (index > -1) {
  49823. this._scene.animationGroups.splice(index, 1);
  49824. }
  49825. };
  49826. return AnimationGroup;
  49827. }());
  49828. BABYLON.AnimationGroup = AnimationGroup;
  49829. })(BABYLON || (BABYLON = {}));
  49830. //# sourceMappingURL=babylon.animationGroup.js.map
  49831. "use strict";
  49832. var BABYLON;
  49833. (function (BABYLON) {
  49834. var RuntimeAnimation = /** @class */ (function () {
  49835. /**
  49836. * Create a new RuntimeAnimation object
  49837. * @param target defines the target of the animation
  49838. * @param animation defines the source {BABYLON.Animation} object
  49839. * @param scene defines the hosting scene
  49840. * @param host defines the initiating Animatable
  49841. */
  49842. function RuntimeAnimation(target, animation, scene, host) {
  49843. this._currentFrame = 0;
  49844. this._offsetsCache = {};
  49845. this._highLimitsCache = {};
  49846. this._stopped = false;
  49847. this._blendingFactor = 0;
  49848. this._targetPath = "";
  49849. this._weight = 1.0;
  49850. this._ratioOffset = 0;
  49851. this._previousDelay = 0;
  49852. this._previousRatio = 0;
  49853. this._animation = animation;
  49854. this._target = target;
  49855. this._scene = scene;
  49856. this._host = host;
  49857. animation._runtimeAnimations.push(this);
  49858. }
  49859. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  49860. /**
  49861. * Gets the current frame
  49862. */
  49863. get: function () {
  49864. return this._currentFrame;
  49865. },
  49866. enumerable: true,
  49867. configurable: true
  49868. });
  49869. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  49870. /**
  49871. * Gets the weight of the runtime animation
  49872. */
  49873. get: function () {
  49874. return this._weight;
  49875. },
  49876. enumerable: true,
  49877. configurable: true
  49878. });
  49879. Object.defineProperty(RuntimeAnimation.prototype, "originalValue", {
  49880. /**
  49881. * Gets the original value of the runtime animation
  49882. */
  49883. get: function () {
  49884. return this._originalValue;
  49885. },
  49886. enumerable: true,
  49887. configurable: true
  49888. });
  49889. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  49890. /**
  49891. * Gets the current value of the runtime animation
  49892. */
  49893. get: function () {
  49894. return this._currentValue;
  49895. },
  49896. enumerable: true,
  49897. configurable: true
  49898. });
  49899. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  49900. /**
  49901. * Gets the path where to store the animated value in the target
  49902. */
  49903. get: function () {
  49904. return this._targetPath;
  49905. },
  49906. enumerable: true,
  49907. configurable: true
  49908. });
  49909. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  49910. /**
  49911. * Gets the actual target of the runtime animation
  49912. */
  49913. get: function () {
  49914. return this._activeTarget;
  49915. },
  49916. enumerable: true,
  49917. configurable: true
  49918. });
  49919. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  49920. get: function () {
  49921. return this._animation;
  49922. },
  49923. enumerable: true,
  49924. configurable: true
  49925. });
  49926. RuntimeAnimation.prototype.reset = function () {
  49927. this._offsetsCache = {};
  49928. this._highLimitsCache = {};
  49929. this._currentFrame = 0;
  49930. this._blendingFactor = 0;
  49931. this._originalValue = null;
  49932. };
  49933. RuntimeAnimation.prototype.isStopped = function () {
  49934. return this._stopped;
  49935. };
  49936. RuntimeAnimation.prototype.dispose = function () {
  49937. var index = this._animation.runtimeAnimations.indexOf(this);
  49938. if (index > -1) {
  49939. this._animation.runtimeAnimations.splice(index, 1);
  49940. }
  49941. };
  49942. RuntimeAnimation.prototype._getKeyValue = function (value) {
  49943. if (typeof value === "function") {
  49944. return value();
  49945. }
  49946. return value;
  49947. };
  49948. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  49949. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  49950. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  49951. }
  49952. this._currentFrame = currentFrame;
  49953. var keys = this._animation.getKeys();
  49954. // Try to get a hash to find the right key
  49955. 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));
  49956. if (keys[startKeyIndex].frame >= currentFrame) {
  49957. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  49958. startKeyIndex--;
  49959. }
  49960. }
  49961. for (var key = startKeyIndex; key < keys.length; key++) {
  49962. var endKey = keys[key + 1];
  49963. if (endKey.frame >= currentFrame) {
  49964. var startKey = keys[key];
  49965. var startValue = this._getKeyValue(startKey.value);
  49966. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  49967. return startValue;
  49968. }
  49969. var endValue = this._getKeyValue(endKey.value);
  49970. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  49971. var frameDelta = endKey.frame - startKey.frame;
  49972. // gradient : percent of currentFrame between the frame inf and the frame sup
  49973. var gradient = (currentFrame - startKey.frame) / frameDelta;
  49974. // check for easingFunction and correction of gradient
  49975. var easingFunction = this._animation.getEasingFunction();
  49976. if (easingFunction != null) {
  49977. gradient = easingFunction.ease(gradient);
  49978. }
  49979. switch (this._animation.dataType) {
  49980. // Float
  49981. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  49982. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  49983. switch (loopMode) {
  49984. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  49985. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  49986. return floatValue;
  49987. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  49988. return offsetValue * repeatCount + floatValue;
  49989. }
  49990. break;
  49991. // Quaternion
  49992. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  49993. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  49994. switch (loopMode) {
  49995. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  49996. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  49997. return quatValue;
  49998. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  49999. return quatValue.add(offsetValue.scale(repeatCount));
  50000. }
  50001. return quatValue;
  50002. // Vector3
  50003. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  50004. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  50005. switch (loopMode) {
  50006. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50007. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50008. return vec3Value;
  50009. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50010. return vec3Value.add(offsetValue.scale(repeatCount));
  50011. }
  50012. // Vector2
  50013. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  50014. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  50015. switch (loopMode) {
  50016. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50017. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50018. return vec2Value;
  50019. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50020. return vec2Value.add(offsetValue.scale(repeatCount));
  50021. }
  50022. // Size
  50023. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  50024. switch (loopMode) {
  50025. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50026. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50027. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  50028. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50029. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50030. }
  50031. // Color3
  50032. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  50033. switch (loopMode) {
  50034. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50035. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50036. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  50037. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50038. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50039. }
  50040. // Matrix
  50041. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  50042. switch (loopMode) {
  50043. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50044. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50045. if (BABYLON.Animation.AllowMatricesInterpolation) {
  50046. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  50047. }
  50048. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50049. return startValue;
  50050. }
  50051. default:
  50052. break;
  50053. }
  50054. break;
  50055. }
  50056. }
  50057. return this._getKeyValue(keys[keys.length - 1].value);
  50058. };
  50059. /**
  50060. * Affect the interpolated value to the target
  50061. * @param currentValue defines the value computed by the animation
  50062. * @param weight defines the weight to apply to this value
  50063. */
  50064. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  50065. if (weight === void 0) { weight = 1.0; }
  50066. // Set value
  50067. var path;
  50068. var destination;
  50069. var targetPropertyPath = this._animation.targetPropertyPath;
  50070. if (targetPropertyPath.length > 1) {
  50071. var property = this._target[targetPropertyPath[0]];
  50072. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  50073. property = property[targetPropertyPath[index]];
  50074. }
  50075. path = targetPropertyPath[targetPropertyPath.length - 1];
  50076. destination = property;
  50077. }
  50078. else {
  50079. path = targetPropertyPath[0];
  50080. destination = this._target;
  50081. }
  50082. this._targetPath = path;
  50083. this._activeTarget = destination;
  50084. this._weight = weight;
  50085. // Blending
  50086. var enableBlending = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  50087. var blendingSpeed = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  50088. if (enableBlending && this._blendingFactor <= 1.0) {
  50089. if (!this._originalBlendValue) {
  50090. var originalValue = destination[path];
  50091. if (originalValue.clone) {
  50092. this._originalBlendValue = originalValue.clone();
  50093. }
  50094. else {
  50095. this._originalBlendValue = originalValue;
  50096. }
  50097. }
  50098. }
  50099. if (weight !== -1.0) {
  50100. if (!this._originalValue) {
  50101. var originalValue = void 0;
  50102. if (destination.getRestPose) {
  50103. originalValue = destination.getRestPose();
  50104. }
  50105. else {
  50106. originalValue = destination[path];
  50107. }
  50108. if (originalValue.clone) {
  50109. this._originalValue = originalValue.clone();
  50110. }
  50111. else {
  50112. this._originalValue = originalValue;
  50113. }
  50114. }
  50115. }
  50116. if (enableBlending && this._blendingFactor <= 1.0) {
  50117. if (this._originalBlendValue.prototype) {
  50118. if (this._originalBlendValue.prototype.Lerp) {
  50119. this._currentValue = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  50120. }
  50121. else {
  50122. this._currentValue = currentValue;
  50123. }
  50124. }
  50125. else if (this._originalBlendValue.m) {
  50126. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50127. }
  50128. else {
  50129. this._currentValue = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  50130. }
  50131. this._blendingFactor += blendingSpeed;
  50132. }
  50133. else {
  50134. this._currentValue = currentValue;
  50135. }
  50136. if (weight !== -1.0) {
  50137. this._scene._registerTargetForLateAnimationBinding(this);
  50138. }
  50139. else {
  50140. destination[path] = this._currentValue;
  50141. }
  50142. if (this._target.markAsDirty) {
  50143. this._target.markAsDirty(this._animation.targetProperty);
  50144. }
  50145. };
  50146. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  50147. if (this._target && this._target.animationPropertiesOverride) {
  50148. return this._target.animationPropertiesOverride.loopMode;
  50149. }
  50150. return this._animation.loopMode;
  50151. };
  50152. /**
  50153. * Move the current animation to a given frame
  50154. * @param frame defines the frame to move to
  50155. */
  50156. RuntimeAnimation.prototype.goToFrame = function (frame) {
  50157. var keys = this._animation.getKeys();
  50158. if (frame < keys[0].frame) {
  50159. frame = keys[0].frame;
  50160. }
  50161. else if (frame > keys[keys.length - 1].frame) {
  50162. frame = keys[keys.length - 1].frame;
  50163. }
  50164. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  50165. this.setValue(currentValue, -1);
  50166. };
  50167. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  50168. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  50169. this._ratioOffset = this._previousRatio - newRatio;
  50170. };
  50171. /**
  50172. * Execute the current animation
  50173. * @param delay defines the delay to add to the current frame
  50174. * @param from defines the lower bound of the animation range
  50175. * @param to defines the upper bound of the animation range
  50176. * @param loop defines if the current animation must loop
  50177. * @param speedRatio defines the current speed ratio
  50178. * @param weight defines the weight of the animation (default is -1 so no weight)
  50179. * @returns a boolean indicating if the animation has ended
  50180. */
  50181. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  50182. if (weight === void 0) { weight = -1.0; }
  50183. var targetPropertyPath = this._animation.targetPropertyPath;
  50184. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  50185. this._stopped = true;
  50186. return false;
  50187. }
  50188. var returnValue = true;
  50189. var keys = this._animation.getKeys();
  50190. // Adding a start key at frame 0 if missing
  50191. if (keys[0].frame !== 0) {
  50192. var newKey = { frame: 0, value: keys[0].value };
  50193. keys.splice(0, 0, newKey);
  50194. }
  50195. // Check limits
  50196. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  50197. from = keys[0].frame;
  50198. }
  50199. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  50200. to = keys[keys.length - 1].frame;
  50201. }
  50202. //to and from cannot be the same key
  50203. if (from === to) {
  50204. if (from > keys[0].frame) {
  50205. from--;
  50206. }
  50207. else if (to < keys[keys.length - 1].frame) {
  50208. to++;
  50209. }
  50210. }
  50211. // Compute ratio
  50212. var range = to - from;
  50213. var offsetValue;
  50214. // ratio represents the frame delta between from and to
  50215. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  50216. var highLimitValue = 0;
  50217. this._previousDelay = delay;
  50218. this._previousRatio = ratio;
  50219. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  50220. returnValue = false;
  50221. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  50222. }
  50223. else {
  50224. // Get max value if required
  50225. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  50226. var keyOffset = to.toString() + from.toString();
  50227. if (!this._offsetsCache[keyOffset]) {
  50228. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  50229. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  50230. switch (this._animation.dataType) {
  50231. // Float
  50232. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  50233. this._offsetsCache[keyOffset] = toValue - fromValue;
  50234. break;
  50235. // Quaternion
  50236. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  50237. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50238. break;
  50239. // Vector3
  50240. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  50241. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50242. // Vector2
  50243. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  50244. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50245. // Size
  50246. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  50247. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50248. // Color3
  50249. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  50250. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50251. default:
  50252. break;
  50253. }
  50254. this._highLimitsCache[keyOffset] = toValue;
  50255. }
  50256. highLimitValue = this._highLimitsCache[keyOffset];
  50257. offsetValue = this._offsetsCache[keyOffset];
  50258. }
  50259. }
  50260. if (offsetValue === undefined) {
  50261. switch (this._animation.dataType) {
  50262. // Float
  50263. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  50264. offsetValue = 0;
  50265. break;
  50266. // Quaternion
  50267. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  50268. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  50269. break;
  50270. // Vector3
  50271. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  50272. offsetValue = BABYLON.Vector3.Zero();
  50273. break;
  50274. // Vector2
  50275. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  50276. offsetValue = BABYLON.Vector2.Zero();
  50277. break;
  50278. // Size
  50279. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  50280. offsetValue = BABYLON.Size.Zero();
  50281. break;
  50282. // Color3
  50283. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  50284. offsetValue = BABYLON.Color3.Black();
  50285. }
  50286. }
  50287. // Compute value
  50288. var repeatCount = (ratio / range) >> 0;
  50289. var currentFrame = returnValue ? from + ratio % range : to;
  50290. // Need to normalize?
  50291. if (this._host && this._host.syncRoot) {
  50292. var syncRoot = this._host.syncRoot;
  50293. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  50294. currentFrame = from + (to - from) * hostNormalizedFrame;
  50295. }
  50296. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  50297. // Set value
  50298. this.setValue(currentValue, weight);
  50299. // Check events
  50300. var events = this._animation.getEvents();
  50301. for (var index = 0; index < events.length; index++) {
  50302. // Make sure current frame has passed event frame and that event frame is within the current range
  50303. // Also, handle both forward and reverse animations
  50304. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  50305. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  50306. var event = events[index];
  50307. if (!event.isDone) {
  50308. // If event should be done only once, remove it.
  50309. if (event.onlyOnce) {
  50310. events.splice(index, 1);
  50311. index--;
  50312. }
  50313. event.isDone = true;
  50314. event.action();
  50315. } // Don't do anything if the event has already be done.
  50316. }
  50317. else if (events[index].isDone && !events[index].onlyOnce) {
  50318. // reset event, the animation is looping
  50319. events[index].isDone = false;
  50320. }
  50321. }
  50322. if (!returnValue) {
  50323. this._stopped = true;
  50324. }
  50325. return returnValue;
  50326. };
  50327. return RuntimeAnimation;
  50328. }());
  50329. BABYLON.RuntimeAnimation = RuntimeAnimation;
  50330. })(BABYLON || (BABYLON = {}));
  50331. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  50332. "use strict";
  50333. var BABYLON;
  50334. (function (BABYLON) {
  50335. var Animatable = /** @class */ (function () {
  50336. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  50337. if (fromFrame === void 0) { fromFrame = 0; }
  50338. if (toFrame === void 0) { toFrame = 100; }
  50339. if (loopAnimation === void 0) { loopAnimation = false; }
  50340. if (speedRatio === void 0) { speedRatio = 1.0; }
  50341. this.target = target;
  50342. this.fromFrame = fromFrame;
  50343. this.toFrame = toFrame;
  50344. this.loopAnimation = loopAnimation;
  50345. this.onAnimationEnd = onAnimationEnd;
  50346. this._localDelayOffset = null;
  50347. this._pausedDelay = null;
  50348. this._runtimeAnimations = new Array();
  50349. this._paused = false;
  50350. this._speedRatio = 1;
  50351. this._weight = -1.0;
  50352. this.animationStarted = false;
  50353. if (animations) {
  50354. this.appendAnimations(target, animations);
  50355. }
  50356. this._speedRatio = speedRatio;
  50357. this._scene = scene;
  50358. scene._activeAnimatables.push(this);
  50359. }
  50360. Object.defineProperty(Animatable.prototype, "syncRoot", {
  50361. /**
  50362. * Gets the root Animatable used to synchronize and normalize animations
  50363. */
  50364. get: function () {
  50365. return this._syncRoot;
  50366. },
  50367. enumerable: true,
  50368. configurable: true
  50369. });
  50370. Object.defineProperty(Animatable.prototype, "masterFrame", {
  50371. /**
  50372. * Gets the current frame of the first RuntimeAnimation
  50373. * Used to synchronize Animatables
  50374. */
  50375. get: function () {
  50376. if (this._runtimeAnimations.length === 0) {
  50377. return 0;
  50378. }
  50379. return this._runtimeAnimations[0].currentFrame;
  50380. },
  50381. enumerable: true,
  50382. configurable: true
  50383. });
  50384. Object.defineProperty(Animatable.prototype, "weight", {
  50385. /**
  50386. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  50387. */
  50388. get: function () {
  50389. return this._weight;
  50390. },
  50391. set: function (value) {
  50392. if (value === -1) {
  50393. this._weight = -1;
  50394. return;
  50395. }
  50396. // Else weight must be in [0, 1] range
  50397. this._weight = Math.min(Math.max(value, 0), 1.0);
  50398. },
  50399. enumerable: true,
  50400. configurable: true
  50401. });
  50402. Object.defineProperty(Animatable.prototype, "speedRatio", {
  50403. /**
  50404. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  50405. */
  50406. get: function () {
  50407. return this._speedRatio;
  50408. },
  50409. set: function (value) {
  50410. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  50411. var animation = this._runtimeAnimations[index];
  50412. animation._prepareForSpeedRatioChange(value);
  50413. }
  50414. this._speedRatio = value;
  50415. },
  50416. enumerable: true,
  50417. configurable: true
  50418. });
  50419. // Methods
  50420. /**
  50421. * Synchronize and normalize current Animatable with a source Animatable.
  50422. * This is useful when using animation weights and when animations are not of the same length
  50423. * @param root defines the root Animatable to synchronize with
  50424. * @returns the current Animatable
  50425. */
  50426. Animatable.prototype.syncWith = function (root) {
  50427. this._syncRoot = root;
  50428. if (root) {
  50429. // Make sure this animatable will animate after the root
  50430. var index = this._scene._activeAnimatables.indexOf(this);
  50431. if (index > -1) {
  50432. this._scene._activeAnimatables.splice(index, 1);
  50433. this._scene._activeAnimatables.push(this);
  50434. }
  50435. }
  50436. return this;
  50437. };
  50438. Animatable.prototype.getAnimations = function () {
  50439. return this._runtimeAnimations;
  50440. };
  50441. Animatable.prototype.appendAnimations = function (target, animations) {
  50442. for (var index = 0; index < animations.length; index++) {
  50443. var animation = animations[index];
  50444. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  50445. }
  50446. };
  50447. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  50448. var runtimeAnimations = this._runtimeAnimations;
  50449. for (var index = 0; index < runtimeAnimations.length; index++) {
  50450. if (runtimeAnimations[index].animation.targetProperty === property) {
  50451. return runtimeAnimations[index].animation;
  50452. }
  50453. }
  50454. return null;
  50455. };
  50456. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  50457. var runtimeAnimations = this._runtimeAnimations;
  50458. for (var index = 0; index < runtimeAnimations.length; index++) {
  50459. if (runtimeAnimations[index].animation.targetProperty === property) {
  50460. return runtimeAnimations[index];
  50461. }
  50462. }
  50463. return null;
  50464. };
  50465. Animatable.prototype.reset = function () {
  50466. var runtimeAnimations = this._runtimeAnimations;
  50467. for (var index = 0; index < runtimeAnimations.length; index++) {
  50468. runtimeAnimations[index].reset();
  50469. }
  50470. // Reset to original value
  50471. for (index = 0; index < runtimeAnimations.length; index++) {
  50472. var animation = runtimeAnimations[index];
  50473. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  50474. }
  50475. this._localDelayOffset = null;
  50476. this._pausedDelay = null;
  50477. };
  50478. Animatable.prototype.enableBlending = function (blendingSpeed) {
  50479. var runtimeAnimations = this._runtimeAnimations;
  50480. for (var index = 0; index < runtimeAnimations.length; index++) {
  50481. runtimeAnimations[index].animation.enableBlending = true;
  50482. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  50483. }
  50484. };
  50485. Animatable.prototype.disableBlending = function () {
  50486. var runtimeAnimations = this._runtimeAnimations;
  50487. for (var index = 0; index < runtimeAnimations.length; index++) {
  50488. runtimeAnimations[index].animation.enableBlending = false;
  50489. }
  50490. };
  50491. Animatable.prototype.goToFrame = function (frame) {
  50492. var runtimeAnimations = this._runtimeAnimations;
  50493. if (runtimeAnimations[0]) {
  50494. var fps = runtimeAnimations[0].animation.framePerSecond;
  50495. var currentFrame = runtimeAnimations[0].currentFrame;
  50496. var adjustTime = frame - currentFrame;
  50497. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  50498. if (this._localDelayOffset === null) {
  50499. this._localDelayOffset = 0;
  50500. }
  50501. this._localDelayOffset -= delay;
  50502. }
  50503. for (var index = 0; index < runtimeAnimations.length; index++) {
  50504. runtimeAnimations[index].goToFrame(frame);
  50505. }
  50506. };
  50507. Animatable.prototype.pause = function () {
  50508. if (this._paused) {
  50509. return;
  50510. }
  50511. this._paused = true;
  50512. };
  50513. Animatable.prototype.restart = function () {
  50514. this._paused = false;
  50515. };
  50516. Animatable.prototype.stop = function (animationName) {
  50517. if (animationName) {
  50518. var idx = this._scene._activeAnimatables.indexOf(this);
  50519. if (idx > -1) {
  50520. var runtimeAnimations = this._runtimeAnimations;
  50521. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  50522. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  50523. continue;
  50524. }
  50525. runtimeAnimations[index].dispose();
  50526. runtimeAnimations.splice(index, 1);
  50527. }
  50528. if (runtimeAnimations.length == 0) {
  50529. this._scene._activeAnimatables.splice(idx, 1);
  50530. if (this.onAnimationEnd) {
  50531. this.onAnimationEnd();
  50532. }
  50533. }
  50534. }
  50535. }
  50536. else {
  50537. var index = this._scene._activeAnimatables.indexOf(this);
  50538. if (index > -1) {
  50539. this._scene._activeAnimatables.splice(index, 1);
  50540. var runtimeAnimations = this._runtimeAnimations;
  50541. for (var index = 0; index < runtimeAnimations.length; index++) {
  50542. runtimeAnimations[index].dispose();
  50543. }
  50544. if (this.onAnimationEnd) {
  50545. this.onAnimationEnd();
  50546. }
  50547. }
  50548. }
  50549. };
  50550. Animatable.prototype._animate = function (delay) {
  50551. if (this._paused) {
  50552. this.animationStarted = false;
  50553. if (this._pausedDelay === null) {
  50554. this._pausedDelay = delay;
  50555. }
  50556. return true;
  50557. }
  50558. if (this._localDelayOffset === null) {
  50559. this._localDelayOffset = delay;
  50560. this._pausedDelay = null;
  50561. }
  50562. else if (this._pausedDelay !== null) {
  50563. this._localDelayOffset += delay - this._pausedDelay;
  50564. this._pausedDelay = null;
  50565. }
  50566. if (this._weight === 0) {
  50567. return true;
  50568. }
  50569. // Animating
  50570. var running = false;
  50571. var runtimeAnimations = this._runtimeAnimations;
  50572. var index;
  50573. for (index = 0; index < runtimeAnimations.length; index++) {
  50574. var animation = runtimeAnimations[index];
  50575. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  50576. running = running || isRunning;
  50577. }
  50578. this.animationStarted = running;
  50579. if (!running) {
  50580. // Remove from active animatables
  50581. index = this._scene._activeAnimatables.indexOf(this);
  50582. this._scene._activeAnimatables.splice(index, 1);
  50583. // Dispose all runtime animations
  50584. for (index = 0; index < runtimeAnimations.length; index++) {
  50585. runtimeAnimations[index].dispose();
  50586. }
  50587. }
  50588. if (!running && this.onAnimationEnd) {
  50589. this.onAnimationEnd();
  50590. this.onAnimationEnd = null;
  50591. }
  50592. return running;
  50593. };
  50594. return Animatable;
  50595. }());
  50596. BABYLON.Animatable = Animatable;
  50597. })(BABYLON || (BABYLON = {}));
  50598. //# sourceMappingURL=babylon.animatable.js.map
  50599. "use strict";
  50600. var BABYLON;
  50601. (function (BABYLON) {
  50602. var EasingFunction = /** @class */ (function () {
  50603. function EasingFunction() {
  50604. // Properties
  50605. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  50606. }
  50607. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  50608. get: function () {
  50609. return EasingFunction._EASINGMODE_EASEIN;
  50610. },
  50611. enumerable: true,
  50612. configurable: true
  50613. });
  50614. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  50615. get: function () {
  50616. return EasingFunction._EASINGMODE_EASEOUT;
  50617. },
  50618. enumerable: true,
  50619. configurable: true
  50620. });
  50621. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  50622. get: function () {
  50623. return EasingFunction._EASINGMODE_EASEINOUT;
  50624. },
  50625. enumerable: true,
  50626. configurable: true
  50627. });
  50628. EasingFunction.prototype.setEasingMode = function (easingMode) {
  50629. var n = Math.min(Math.max(easingMode, 0), 2);
  50630. this._easingMode = n;
  50631. };
  50632. EasingFunction.prototype.getEasingMode = function () {
  50633. return this._easingMode;
  50634. };
  50635. EasingFunction.prototype.easeInCore = function (gradient) {
  50636. throw new Error('You must implement this method');
  50637. };
  50638. EasingFunction.prototype.ease = function (gradient) {
  50639. switch (this._easingMode) {
  50640. case EasingFunction.EASINGMODE_EASEIN:
  50641. return this.easeInCore(gradient);
  50642. case EasingFunction.EASINGMODE_EASEOUT:
  50643. return (1 - this.easeInCore(1 - gradient));
  50644. }
  50645. if (gradient >= 0.5) {
  50646. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  50647. }
  50648. return (this.easeInCore(gradient * 2) * 0.5);
  50649. };
  50650. //Statics
  50651. EasingFunction._EASINGMODE_EASEIN = 0;
  50652. EasingFunction._EASINGMODE_EASEOUT = 1;
  50653. EasingFunction._EASINGMODE_EASEINOUT = 2;
  50654. return EasingFunction;
  50655. }());
  50656. BABYLON.EasingFunction = EasingFunction;
  50657. var CircleEase = /** @class */ (function (_super) {
  50658. __extends(CircleEase, _super);
  50659. function CircleEase() {
  50660. return _super !== null && _super.apply(this, arguments) || this;
  50661. }
  50662. CircleEase.prototype.easeInCore = function (gradient) {
  50663. gradient = Math.max(0, Math.min(1, gradient));
  50664. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  50665. };
  50666. return CircleEase;
  50667. }(EasingFunction));
  50668. BABYLON.CircleEase = CircleEase;
  50669. var BackEase = /** @class */ (function (_super) {
  50670. __extends(BackEase, _super);
  50671. function BackEase(amplitude) {
  50672. if (amplitude === void 0) { amplitude = 1; }
  50673. var _this = _super.call(this) || this;
  50674. _this.amplitude = amplitude;
  50675. return _this;
  50676. }
  50677. BackEase.prototype.easeInCore = function (gradient) {
  50678. var num = Math.max(0, this.amplitude);
  50679. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  50680. };
  50681. return BackEase;
  50682. }(EasingFunction));
  50683. BABYLON.BackEase = BackEase;
  50684. var BounceEase = /** @class */ (function (_super) {
  50685. __extends(BounceEase, _super);
  50686. function BounceEase(bounces, bounciness) {
  50687. if (bounces === void 0) { bounces = 3; }
  50688. if (bounciness === void 0) { bounciness = 2; }
  50689. var _this = _super.call(this) || this;
  50690. _this.bounces = bounces;
  50691. _this.bounciness = bounciness;
  50692. return _this;
  50693. }
  50694. BounceEase.prototype.easeInCore = function (gradient) {
  50695. var y = Math.max(0.0, this.bounces);
  50696. var bounciness = this.bounciness;
  50697. if (bounciness <= 1.0) {
  50698. bounciness = 1.001;
  50699. }
  50700. var num9 = Math.pow(bounciness, y);
  50701. var num5 = 1.0 - bounciness;
  50702. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  50703. var num15 = gradient * num4;
  50704. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  50705. var num3 = Math.floor(num65);
  50706. var num13 = num3 + 1.0;
  50707. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  50708. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  50709. var num7 = (num8 + num12) * 0.5;
  50710. var num6 = gradient - num7;
  50711. var num2 = num7 - num8;
  50712. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  50713. };
  50714. return BounceEase;
  50715. }(EasingFunction));
  50716. BABYLON.BounceEase = BounceEase;
  50717. var CubicEase = /** @class */ (function (_super) {
  50718. __extends(CubicEase, _super);
  50719. function CubicEase() {
  50720. return _super !== null && _super.apply(this, arguments) || this;
  50721. }
  50722. CubicEase.prototype.easeInCore = function (gradient) {
  50723. return (gradient * gradient * gradient);
  50724. };
  50725. return CubicEase;
  50726. }(EasingFunction));
  50727. BABYLON.CubicEase = CubicEase;
  50728. var ElasticEase = /** @class */ (function (_super) {
  50729. __extends(ElasticEase, _super);
  50730. function ElasticEase(oscillations, springiness) {
  50731. if (oscillations === void 0) { oscillations = 3; }
  50732. if (springiness === void 0) { springiness = 3; }
  50733. var _this = _super.call(this) || this;
  50734. _this.oscillations = oscillations;
  50735. _this.springiness = springiness;
  50736. return _this;
  50737. }
  50738. ElasticEase.prototype.easeInCore = function (gradient) {
  50739. var num2;
  50740. var num3 = Math.max(0.0, this.oscillations);
  50741. var num = Math.max(0.0, this.springiness);
  50742. if (num == 0) {
  50743. num2 = gradient;
  50744. }
  50745. else {
  50746. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  50747. }
  50748. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  50749. };
  50750. return ElasticEase;
  50751. }(EasingFunction));
  50752. BABYLON.ElasticEase = ElasticEase;
  50753. var ExponentialEase = /** @class */ (function (_super) {
  50754. __extends(ExponentialEase, _super);
  50755. function ExponentialEase(exponent) {
  50756. if (exponent === void 0) { exponent = 2; }
  50757. var _this = _super.call(this) || this;
  50758. _this.exponent = exponent;
  50759. return _this;
  50760. }
  50761. ExponentialEase.prototype.easeInCore = function (gradient) {
  50762. if (this.exponent <= 0) {
  50763. return gradient;
  50764. }
  50765. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  50766. };
  50767. return ExponentialEase;
  50768. }(EasingFunction));
  50769. BABYLON.ExponentialEase = ExponentialEase;
  50770. var PowerEase = /** @class */ (function (_super) {
  50771. __extends(PowerEase, _super);
  50772. function PowerEase(power) {
  50773. if (power === void 0) { power = 2; }
  50774. var _this = _super.call(this) || this;
  50775. _this.power = power;
  50776. return _this;
  50777. }
  50778. PowerEase.prototype.easeInCore = function (gradient) {
  50779. var y = Math.max(0.0, this.power);
  50780. return Math.pow(gradient, y);
  50781. };
  50782. return PowerEase;
  50783. }(EasingFunction));
  50784. BABYLON.PowerEase = PowerEase;
  50785. var QuadraticEase = /** @class */ (function (_super) {
  50786. __extends(QuadraticEase, _super);
  50787. function QuadraticEase() {
  50788. return _super !== null && _super.apply(this, arguments) || this;
  50789. }
  50790. QuadraticEase.prototype.easeInCore = function (gradient) {
  50791. return (gradient * gradient);
  50792. };
  50793. return QuadraticEase;
  50794. }(EasingFunction));
  50795. BABYLON.QuadraticEase = QuadraticEase;
  50796. var QuarticEase = /** @class */ (function (_super) {
  50797. __extends(QuarticEase, _super);
  50798. function QuarticEase() {
  50799. return _super !== null && _super.apply(this, arguments) || this;
  50800. }
  50801. QuarticEase.prototype.easeInCore = function (gradient) {
  50802. return (gradient * gradient * gradient * gradient);
  50803. };
  50804. return QuarticEase;
  50805. }(EasingFunction));
  50806. BABYLON.QuarticEase = QuarticEase;
  50807. var QuinticEase = /** @class */ (function (_super) {
  50808. __extends(QuinticEase, _super);
  50809. function QuinticEase() {
  50810. return _super !== null && _super.apply(this, arguments) || this;
  50811. }
  50812. QuinticEase.prototype.easeInCore = function (gradient) {
  50813. return (gradient * gradient * gradient * gradient * gradient);
  50814. };
  50815. return QuinticEase;
  50816. }(EasingFunction));
  50817. BABYLON.QuinticEase = QuinticEase;
  50818. var SineEase = /** @class */ (function (_super) {
  50819. __extends(SineEase, _super);
  50820. function SineEase() {
  50821. return _super !== null && _super.apply(this, arguments) || this;
  50822. }
  50823. SineEase.prototype.easeInCore = function (gradient) {
  50824. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  50825. };
  50826. return SineEase;
  50827. }(EasingFunction));
  50828. BABYLON.SineEase = SineEase;
  50829. var BezierCurveEase = /** @class */ (function (_super) {
  50830. __extends(BezierCurveEase, _super);
  50831. function BezierCurveEase(x1, y1, x2, y2) {
  50832. if (x1 === void 0) { x1 = 0; }
  50833. if (y1 === void 0) { y1 = 0; }
  50834. if (x2 === void 0) { x2 = 1; }
  50835. if (y2 === void 0) { y2 = 1; }
  50836. var _this = _super.call(this) || this;
  50837. _this.x1 = x1;
  50838. _this.y1 = y1;
  50839. _this.x2 = x2;
  50840. _this.y2 = y2;
  50841. return _this;
  50842. }
  50843. BezierCurveEase.prototype.easeInCore = function (gradient) {
  50844. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  50845. };
  50846. return BezierCurveEase;
  50847. }(EasingFunction));
  50848. BABYLON.BezierCurveEase = BezierCurveEase;
  50849. })(BABYLON || (BABYLON = {}));
  50850. //# sourceMappingURL=babylon.easing.js.map
  50851. "use strict";
  50852. var BABYLON;
  50853. (function (BABYLON) {
  50854. /**
  50855. * A Condition applied to an Action
  50856. */
  50857. var Condition = /** @class */ (function () {
  50858. /**
  50859. * Creates a new Condition
  50860. * @param actionManager the manager of the action the condition is applied to
  50861. */
  50862. function Condition(actionManager) {
  50863. this._actionManager = actionManager;
  50864. }
  50865. /**
  50866. * Check if the current condition is valid
  50867. * @returns a boolean
  50868. */
  50869. Condition.prototype.isValid = function () {
  50870. return true;
  50871. };
  50872. /**
  50873. * Internal only
  50874. * @ignore
  50875. */
  50876. Condition.prototype._getProperty = function (propertyPath) {
  50877. return this._actionManager._getProperty(propertyPath);
  50878. };
  50879. /**
  50880. * Internal only
  50881. * @ignore
  50882. */
  50883. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  50884. return this._actionManager._getEffectiveTarget(target, propertyPath);
  50885. };
  50886. /**
  50887. * Serialize placeholder for child classes
  50888. * @returns the serialized object
  50889. */
  50890. Condition.prototype.serialize = function () {
  50891. };
  50892. /**
  50893. * Internal only
  50894. * @ignore
  50895. */
  50896. Condition.prototype._serialize = function (serializedCondition) {
  50897. return {
  50898. type: 2,
  50899. children: [],
  50900. name: serializedCondition.name,
  50901. properties: serializedCondition.properties
  50902. };
  50903. };
  50904. return Condition;
  50905. }());
  50906. BABYLON.Condition = Condition;
  50907. /**
  50908. * Defines specific conditional operators as extensions of Condition
  50909. */
  50910. var ValueCondition = /** @class */ (function (_super) {
  50911. __extends(ValueCondition, _super);
  50912. /**
  50913. * Creates a new ValueCondition
  50914. * @param actionManager manager for the action the condition applies to
  50915. * @param target for the action
  50916. * @param propertyPath path to specify the property of the target the conditional operator uses
  50917. * @param value the vale compared by the conditional operator against the current value of the property
  50918. * @param operator the conditional operator, default {BABYLON.ValueCondition.IsEqual}
  50919. */
  50920. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  50921. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  50922. var _this = _super.call(this, actionManager) || this;
  50923. _this.propertyPath = propertyPath;
  50924. _this.value = value;
  50925. _this.operator = operator;
  50926. _this._target = target;
  50927. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  50928. _this._property = _this._getProperty(_this.propertyPath);
  50929. return _this;
  50930. }
  50931. Object.defineProperty(ValueCondition, "IsEqual", {
  50932. /**
  50933. * returns the number for IsEqual
  50934. */
  50935. get: function () {
  50936. return ValueCondition._IsEqual;
  50937. },
  50938. enumerable: true,
  50939. configurable: true
  50940. });
  50941. Object.defineProperty(ValueCondition, "IsDifferent", {
  50942. /**
  50943. * Returns the number for IsDifferent
  50944. */
  50945. get: function () {
  50946. return ValueCondition._IsDifferent;
  50947. },
  50948. enumerable: true,
  50949. configurable: true
  50950. });
  50951. Object.defineProperty(ValueCondition, "IsGreater", {
  50952. /**
  50953. * Returns the number for IsGreater
  50954. */
  50955. get: function () {
  50956. return ValueCondition._IsGreater;
  50957. },
  50958. enumerable: true,
  50959. configurable: true
  50960. });
  50961. Object.defineProperty(ValueCondition, "IsLesser", {
  50962. /**
  50963. * Returns the number for IsLesser
  50964. */
  50965. get: function () {
  50966. return ValueCondition._IsLesser;
  50967. },
  50968. enumerable: true,
  50969. configurable: true
  50970. });
  50971. /**
  50972. * Compares the given value with the property value for the specified conditional operator
  50973. * @returns the result of the comparison
  50974. */
  50975. ValueCondition.prototype.isValid = function () {
  50976. switch (this.operator) {
  50977. case ValueCondition.IsGreater:
  50978. return this._effectiveTarget[this._property] > this.value;
  50979. case ValueCondition.IsLesser:
  50980. return this._effectiveTarget[this._property] < this.value;
  50981. case ValueCondition.IsEqual:
  50982. case ValueCondition.IsDifferent:
  50983. var check;
  50984. if (this.value.equals) {
  50985. check = this.value.equals(this._effectiveTarget[this._property]);
  50986. }
  50987. else {
  50988. check = this.value === this._effectiveTarget[this._property];
  50989. }
  50990. return this.operator === ValueCondition.IsEqual ? check : !check;
  50991. }
  50992. return false;
  50993. };
  50994. /**
  50995. * Serialize the ValueCondition into a JSON compatible object
  50996. * @returns serialization object
  50997. */
  50998. ValueCondition.prototype.serialize = function () {
  50999. return this._serialize({
  51000. name: "ValueCondition",
  51001. properties: [
  51002. BABYLON.Action._GetTargetProperty(this._target),
  51003. { name: "propertyPath", value: this.propertyPath },
  51004. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  51005. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  51006. ]
  51007. });
  51008. };
  51009. /**
  51010. * Gets the name of the conditional operator for the ValueCondition
  51011. * @param operator the conditional operator
  51012. * @returns the name
  51013. */
  51014. ValueCondition.GetOperatorName = function (operator) {
  51015. switch (operator) {
  51016. case ValueCondition._IsEqual: return "IsEqual";
  51017. case ValueCondition._IsDifferent: return "IsDifferent";
  51018. case ValueCondition._IsGreater: return "IsGreater";
  51019. case ValueCondition._IsLesser: return "IsLesser";
  51020. default: return "";
  51021. }
  51022. };
  51023. /**
  51024. * Internal only
  51025. * @ignore
  51026. */
  51027. ValueCondition._IsEqual = 0;
  51028. /**
  51029. * Internal only
  51030. * @ignore
  51031. */
  51032. ValueCondition._IsDifferent = 1;
  51033. /**
  51034. * Internal only
  51035. * @ignore
  51036. */
  51037. ValueCondition._IsGreater = 2;
  51038. /**
  51039. * Internal only
  51040. * @ignore
  51041. */
  51042. ValueCondition._IsLesser = 3;
  51043. return ValueCondition;
  51044. }(Condition));
  51045. BABYLON.ValueCondition = ValueCondition;
  51046. /**
  51047. * Defines a predicate condition as an extension of Condition
  51048. */
  51049. var PredicateCondition = /** @class */ (function (_super) {
  51050. __extends(PredicateCondition, _super);
  51051. /**
  51052. * Creates a new {BABYLON.PredicateCondition}
  51053. * @param actionManager manager for the action the condition applies to
  51054. * @param predicate
  51055. */
  51056. function PredicateCondition(actionManager, predicate) {
  51057. var _this = _super.call(this, actionManager) || this;
  51058. _this.predicate = predicate;
  51059. return _this;
  51060. }
  51061. /**
  51062. * @returns the validity of the predicate condition
  51063. */
  51064. PredicateCondition.prototype.isValid = function () {
  51065. return this.predicate();
  51066. };
  51067. return PredicateCondition;
  51068. }(Condition));
  51069. BABYLON.PredicateCondition = PredicateCondition;
  51070. /**
  51071. * Defines a state condition as an extension of {BABYLON.Condition}
  51072. */
  51073. var StateCondition = /** @class */ (function (_super) {
  51074. __extends(StateCondition, _super);
  51075. /**
  51076. * Creates a new {BABYLON.StateCondition}
  51077. * @param actionManager manager for the action the condition applies to
  51078. * @param target of the condition
  51079. * @param value to compare with target state
  51080. */
  51081. function StateCondition(actionManager, target, value) {
  51082. var _this = _super.call(this, actionManager) || this;
  51083. _this.value = value;
  51084. _this._target = target;
  51085. return _this;
  51086. }
  51087. /**
  51088. * @returns the validity of the state
  51089. */
  51090. StateCondition.prototype.isValid = function () {
  51091. return this._target.state === this.value;
  51092. };
  51093. /**
  51094. * Serialize the {BABYLON.StateCondition} into a JSON compatible object
  51095. * @returns serialization object
  51096. */
  51097. StateCondition.prototype.serialize = function () {
  51098. return this._serialize({
  51099. name: "StateCondition",
  51100. properties: [
  51101. BABYLON.Action._GetTargetProperty(this._target),
  51102. { name: "value", value: this.value }
  51103. ]
  51104. });
  51105. };
  51106. return StateCondition;
  51107. }(Condition));
  51108. BABYLON.StateCondition = StateCondition;
  51109. })(BABYLON || (BABYLON = {}));
  51110. //# sourceMappingURL=babylon.condition.js.map
  51111. "use strict";
  51112. var BABYLON;
  51113. (function (BABYLON) {
  51114. /**
  51115. * The action to be carried out following a trigger
  51116. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  51117. */
  51118. var Action = /** @class */ (function () {
  51119. /**
  51120. * Creates a new Action
  51121. * @param triggerOptions the trigger, with or without parameters, for the action
  51122. * @param condition an optional determinant of action
  51123. */
  51124. function Action(triggerOptions, condition) {
  51125. this.triggerOptions = triggerOptions;
  51126. /**
  51127. * An event triggered prior to action being executed.
  51128. */
  51129. this.onBeforeExecuteObservable = new BABYLON.Observable();
  51130. if (triggerOptions.parameter) {
  51131. this.trigger = triggerOptions.trigger;
  51132. this._triggerParameter = triggerOptions.parameter;
  51133. }
  51134. else {
  51135. this.trigger = triggerOptions;
  51136. }
  51137. this._nextActiveAction = this;
  51138. this._condition = condition;
  51139. }
  51140. /**
  51141. * Internal only
  51142. * @ignore
  51143. */
  51144. Action.prototype._prepare = function () {
  51145. };
  51146. /**
  51147. * Gets the trigger parameters
  51148. * @returns the trigger parameters
  51149. */
  51150. Action.prototype.getTriggerParameter = function () {
  51151. return this._triggerParameter;
  51152. };
  51153. /**
  51154. * Internal only - executes current action event
  51155. * @ignore
  51156. */
  51157. Action.prototype._executeCurrent = function (evt) {
  51158. if (this._nextActiveAction._condition) {
  51159. var condition = this._nextActiveAction._condition;
  51160. var currentRenderId = this._actionManager.getScene().getRenderId();
  51161. // We cache the current evaluation for the current frame
  51162. if (condition._evaluationId === currentRenderId) {
  51163. if (!condition._currentResult) {
  51164. return;
  51165. }
  51166. }
  51167. else {
  51168. condition._evaluationId = currentRenderId;
  51169. if (!condition.isValid()) {
  51170. condition._currentResult = false;
  51171. return;
  51172. }
  51173. condition._currentResult = true;
  51174. }
  51175. }
  51176. this.onBeforeExecuteObservable.notifyObservers(this);
  51177. this._nextActiveAction.execute(evt);
  51178. this.skipToNextActiveAction();
  51179. };
  51180. /**
  51181. * Execute placeholder for child classes
  51182. * @param evt optional action event
  51183. */
  51184. Action.prototype.execute = function (evt) {
  51185. };
  51186. /**
  51187. * Skips to next active action
  51188. */
  51189. Action.prototype.skipToNextActiveAction = function () {
  51190. if (this._nextActiveAction._child) {
  51191. if (!this._nextActiveAction._child._actionManager) {
  51192. this._nextActiveAction._child._actionManager = this._actionManager;
  51193. }
  51194. this._nextActiveAction = this._nextActiveAction._child;
  51195. }
  51196. else {
  51197. this._nextActiveAction = this;
  51198. }
  51199. };
  51200. /**
  51201. * Adds action to chain of actions, may be a DoNothingAction
  51202. * @param index The index of the attribute.
  51203. * @returns The action passed in
  51204. * @see https://www.babylonjs-playground.com/#1T30HR#0
  51205. */
  51206. Action.prototype.then = function (action) {
  51207. this._child = action;
  51208. action._actionManager = this._actionManager;
  51209. action._prepare();
  51210. return action;
  51211. };
  51212. /**
  51213. * Internal only
  51214. * @ignore
  51215. */
  51216. Action.prototype._getProperty = function (propertyPath) {
  51217. return this._actionManager._getProperty(propertyPath);
  51218. };
  51219. /**
  51220. * Internal only
  51221. * @ignore
  51222. */
  51223. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  51224. return this._actionManager._getEffectiveTarget(target, propertyPath);
  51225. };
  51226. /**
  51227. * Serialize placeholder for child classes
  51228. * @param parent of child
  51229. * @returns the serialized object
  51230. */
  51231. Action.prototype.serialize = function (parent) {
  51232. };
  51233. /**
  51234. * Internal only called by serialize
  51235. * @ignore
  51236. */
  51237. Action.prototype._serialize = function (serializedAction, parent) {
  51238. var serializationObject = {
  51239. type: 1,
  51240. children: [],
  51241. name: serializedAction.name,
  51242. properties: serializedAction.properties || []
  51243. };
  51244. // Serialize child
  51245. if (this._child) {
  51246. this._child.serialize(serializationObject);
  51247. }
  51248. // Check if "this" has a condition
  51249. if (this._condition) {
  51250. var serializedCondition = this._condition.serialize();
  51251. serializedCondition.children.push(serializationObject);
  51252. if (parent) {
  51253. parent.children.push(serializedCondition);
  51254. }
  51255. return serializedCondition;
  51256. }
  51257. if (parent) {
  51258. parent.children.push(serializationObject);
  51259. }
  51260. return serializationObject;
  51261. };
  51262. /**
  51263. * Internal only
  51264. * @ignore
  51265. */
  51266. Action._SerializeValueAsString = function (value) {
  51267. if (typeof value === "number") {
  51268. return value.toString();
  51269. }
  51270. if (typeof value === "boolean") {
  51271. return value ? "true" : "false";
  51272. }
  51273. if (value instanceof BABYLON.Vector2) {
  51274. return value.x + ", " + value.y;
  51275. }
  51276. if (value instanceof BABYLON.Vector3) {
  51277. return value.x + ", " + value.y + ", " + value.z;
  51278. }
  51279. if (value instanceof BABYLON.Color3) {
  51280. return value.r + ", " + value.g + ", " + value.b;
  51281. }
  51282. if (value instanceof BABYLON.Color4) {
  51283. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  51284. }
  51285. return value; // string
  51286. };
  51287. /**
  51288. * Internal only
  51289. * @ignore
  51290. */
  51291. Action._GetTargetProperty = function (target) {
  51292. return {
  51293. name: "target",
  51294. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  51295. : target instanceof BABYLON.Light ? "LightProperties"
  51296. : target instanceof BABYLON.Camera ? "CameraProperties"
  51297. : "SceneProperties",
  51298. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  51299. };
  51300. };
  51301. return Action;
  51302. }());
  51303. BABYLON.Action = Action;
  51304. })(BABYLON || (BABYLON = {}));
  51305. //# sourceMappingURL=babylon.action.js.map
  51306. "use strict";
  51307. var BABYLON;
  51308. (function (BABYLON) {
  51309. /**
  51310. * ActionEvent is the event being sent when an action is triggered.
  51311. */
  51312. var ActionEvent = /** @class */ (function () {
  51313. /**
  51314. * @param source The mesh or sprite that triggered the action.
  51315. * @param pointerX The X mouse cursor position at the time of the event
  51316. * @param pointerY The Y mouse cursor position at the time of the event
  51317. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  51318. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  51319. */
  51320. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  51321. this.source = source;
  51322. this.pointerX = pointerX;
  51323. this.pointerY = pointerY;
  51324. this.meshUnderPointer = meshUnderPointer;
  51325. this.sourceEvent = sourceEvent;
  51326. this.additionalData = additionalData;
  51327. }
  51328. /**
  51329. * Helper function to auto-create an ActionEvent from a source mesh.
  51330. * @param source The source mesh that triggered the event
  51331. * @param evt {Event} The original (browser) event
  51332. */
  51333. ActionEvent.CreateNew = function (source, evt, additionalData) {
  51334. var scene = source.getScene();
  51335. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  51336. };
  51337. /**
  51338. * Helper function to auto-create an ActionEvent from a source mesh.
  51339. * @param source The source sprite that triggered the event
  51340. * @param scene Scene associated with the sprite
  51341. * @param evt {Event} The original (browser) event
  51342. */
  51343. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  51344. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  51345. };
  51346. /**
  51347. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  51348. * @param scene the scene where the event occurred
  51349. * @param evt {Event} The original (browser) event
  51350. */
  51351. ActionEvent.CreateNewFromScene = function (scene, evt) {
  51352. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  51353. };
  51354. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  51355. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  51356. };
  51357. return ActionEvent;
  51358. }());
  51359. BABYLON.ActionEvent = ActionEvent;
  51360. /**
  51361. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  51362. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  51363. */
  51364. var ActionManager = /** @class */ (function () {
  51365. function ActionManager(scene) {
  51366. // Members
  51367. this.actions = new Array();
  51368. this.hoverCursor = '';
  51369. this._scene = scene;
  51370. scene._actionManagers.push(this);
  51371. }
  51372. Object.defineProperty(ActionManager, "NothingTrigger", {
  51373. get: function () {
  51374. return ActionManager._NothingTrigger;
  51375. },
  51376. enumerable: true,
  51377. configurable: true
  51378. });
  51379. Object.defineProperty(ActionManager, "OnPickTrigger", {
  51380. get: function () {
  51381. return ActionManager._OnPickTrigger;
  51382. },
  51383. enumerable: true,
  51384. configurable: true
  51385. });
  51386. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  51387. get: function () {
  51388. return ActionManager._OnLeftPickTrigger;
  51389. },
  51390. enumerable: true,
  51391. configurable: true
  51392. });
  51393. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  51394. get: function () {
  51395. return ActionManager._OnRightPickTrigger;
  51396. },
  51397. enumerable: true,
  51398. configurable: true
  51399. });
  51400. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  51401. get: function () {
  51402. return ActionManager._OnCenterPickTrigger;
  51403. },
  51404. enumerable: true,
  51405. configurable: true
  51406. });
  51407. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  51408. get: function () {
  51409. return ActionManager._OnPickDownTrigger;
  51410. },
  51411. enumerable: true,
  51412. configurable: true
  51413. });
  51414. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  51415. get: function () {
  51416. return ActionManager._OnDoublePickTrigger;
  51417. },
  51418. enumerable: true,
  51419. configurable: true
  51420. });
  51421. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  51422. get: function () {
  51423. return ActionManager._OnPickUpTrigger;
  51424. },
  51425. enumerable: true,
  51426. configurable: true
  51427. });
  51428. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  51429. /// This trigger will only be raised if you also declared a OnPickDown
  51430. get: function () {
  51431. return ActionManager._OnPickOutTrigger;
  51432. },
  51433. enumerable: true,
  51434. configurable: true
  51435. });
  51436. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  51437. get: function () {
  51438. return ActionManager._OnLongPressTrigger;
  51439. },
  51440. enumerable: true,
  51441. configurable: true
  51442. });
  51443. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  51444. get: function () {
  51445. return ActionManager._OnPointerOverTrigger;
  51446. },
  51447. enumerable: true,
  51448. configurable: true
  51449. });
  51450. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  51451. get: function () {
  51452. return ActionManager._OnPointerOutTrigger;
  51453. },
  51454. enumerable: true,
  51455. configurable: true
  51456. });
  51457. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  51458. get: function () {
  51459. return ActionManager._OnEveryFrameTrigger;
  51460. },
  51461. enumerable: true,
  51462. configurable: true
  51463. });
  51464. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  51465. get: function () {
  51466. return ActionManager._OnIntersectionEnterTrigger;
  51467. },
  51468. enumerable: true,
  51469. configurable: true
  51470. });
  51471. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  51472. get: function () {
  51473. return ActionManager._OnIntersectionExitTrigger;
  51474. },
  51475. enumerable: true,
  51476. configurable: true
  51477. });
  51478. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  51479. get: function () {
  51480. return ActionManager._OnKeyDownTrigger;
  51481. },
  51482. enumerable: true,
  51483. configurable: true
  51484. });
  51485. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  51486. get: function () {
  51487. return ActionManager._OnKeyUpTrigger;
  51488. },
  51489. enumerable: true,
  51490. configurable: true
  51491. });
  51492. // Methods
  51493. ActionManager.prototype.dispose = function () {
  51494. var index = this._scene._actionManagers.indexOf(this);
  51495. for (var i = 0; i < this.actions.length; i++) {
  51496. var action = this.actions[i];
  51497. ActionManager.Triggers[action.trigger]--;
  51498. if (ActionManager.Triggers[action.trigger] === 0) {
  51499. delete ActionManager.Triggers[action.trigger];
  51500. }
  51501. }
  51502. if (index > -1) {
  51503. this._scene._actionManagers.splice(index, 1);
  51504. }
  51505. };
  51506. ActionManager.prototype.getScene = function () {
  51507. return this._scene;
  51508. };
  51509. /**
  51510. * Does this action manager handles actions of any of the given triggers
  51511. * @param {number[]} triggers - the triggers to be tested
  51512. * @return {boolean} whether one (or more) of the triggers is handeled
  51513. */
  51514. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  51515. for (var index = 0; index < this.actions.length; index++) {
  51516. var action = this.actions[index];
  51517. if (triggers.indexOf(action.trigger) > -1) {
  51518. return true;
  51519. }
  51520. }
  51521. return false;
  51522. };
  51523. /**
  51524. * Does this action manager handles actions of a given trigger
  51525. * @param {number} trigger - the trigger to be tested
  51526. * @return {boolean} whether the trigger is handeled
  51527. */
  51528. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  51529. for (var index = 0; index < this.actions.length; index++) {
  51530. var action = this.actions[index];
  51531. if (action.trigger === trigger) {
  51532. return true;
  51533. }
  51534. }
  51535. return false;
  51536. };
  51537. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  51538. /**
  51539. * Does this action manager has pointer triggers
  51540. * @return {boolean} whether or not it has pointer triggers
  51541. */
  51542. get: function () {
  51543. for (var index = 0; index < this.actions.length; index++) {
  51544. var action = this.actions[index];
  51545. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  51546. return true;
  51547. }
  51548. }
  51549. return false;
  51550. },
  51551. enumerable: true,
  51552. configurable: true
  51553. });
  51554. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  51555. /**
  51556. * Does this action manager has pick triggers
  51557. * @return {boolean} whether or not it has pick triggers
  51558. */
  51559. get: function () {
  51560. for (var index = 0; index < this.actions.length; index++) {
  51561. var action = this.actions[index];
  51562. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  51563. return true;
  51564. }
  51565. }
  51566. return false;
  51567. },
  51568. enumerable: true,
  51569. configurable: true
  51570. });
  51571. Object.defineProperty(ActionManager, "HasTriggers", {
  51572. /**
  51573. * Does exist one action manager with at least one trigger
  51574. * @return {boolean} whether or not it exists one action manager with one trigger
  51575. **/
  51576. get: function () {
  51577. for (var t in ActionManager.Triggers) {
  51578. if (ActionManager.Triggers.hasOwnProperty(t)) {
  51579. return true;
  51580. }
  51581. }
  51582. return false;
  51583. },
  51584. enumerable: true,
  51585. configurable: true
  51586. });
  51587. Object.defineProperty(ActionManager, "HasPickTriggers", {
  51588. /**
  51589. * Does exist one action manager with at least one pick trigger
  51590. * @return {boolean} whether or not it exists one action manager with one pick trigger
  51591. **/
  51592. get: function () {
  51593. for (var t in ActionManager.Triggers) {
  51594. if (ActionManager.Triggers.hasOwnProperty(t)) {
  51595. var t_int = parseInt(t);
  51596. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  51597. return true;
  51598. }
  51599. }
  51600. }
  51601. return false;
  51602. },
  51603. enumerable: true,
  51604. configurable: true
  51605. });
  51606. /**
  51607. * Does exist one action manager that handles actions of a given trigger
  51608. * @param {number} trigger - the trigger to be tested
  51609. * @return {boolean} whether the trigger is handeled by at least one action manager
  51610. **/
  51611. ActionManager.HasSpecificTrigger = function (trigger) {
  51612. for (var t in ActionManager.Triggers) {
  51613. if (ActionManager.Triggers.hasOwnProperty(t)) {
  51614. var t_int = parseInt(t);
  51615. if (t_int === trigger) {
  51616. return true;
  51617. }
  51618. }
  51619. }
  51620. return false;
  51621. };
  51622. /**
  51623. * Registers an action to this action manager
  51624. * @param {BABYLON.Action} action - the action to be registered
  51625. * @return {BABYLON.Action} the action amended (prepared) after registration
  51626. */
  51627. ActionManager.prototype.registerAction = function (action) {
  51628. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  51629. if (this.getScene().actionManager !== this) {
  51630. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  51631. return null;
  51632. }
  51633. }
  51634. this.actions.push(action);
  51635. if (ActionManager.Triggers[action.trigger]) {
  51636. ActionManager.Triggers[action.trigger]++;
  51637. }
  51638. else {
  51639. ActionManager.Triggers[action.trigger] = 1;
  51640. }
  51641. action._actionManager = this;
  51642. action._prepare();
  51643. return action;
  51644. };
  51645. /**
  51646. * Unregisters an action to this action manager
  51647. * @param action The action to be unregistered
  51648. * @return whether the action has been unregistered
  51649. */
  51650. ActionManager.prototype.unregisterAction = function (action) {
  51651. var index = this.actions.indexOf(action);
  51652. if (index !== -1) {
  51653. this.actions.splice(index, 1);
  51654. ActionManager.Triggers[action.trigger] -= 1;
  51655. if (ActionManager.Triggers[action.trigger] === 0) {
  51656. delete ActionManager.Triggers[action.trigger];
  51657. }
  51658. delete action._actionManager;
  51659. return true;
  51660. }
  51661. return false;
  51662. };
  51663. /**
  51664. * Process a specific trigger
  51665. * @param {number} trigger - the trigger to process
  51666. * @param evt {BABYLON.ActionEvent} the event details to be processed
  51667. */
  51668. ActionManager.prototype.processTrigger = function (trigger, evt) {
  51669. for (var index = 0; index < this.actions.length; index++) {
  51670. var action = this.actions[index];
  51671. if (action.trigger === trigger) {
  51672. if (evt) {
  51673. if (trigger === ActionManager.OnKeyUpTrigger
  51674. || trigger === ActionManager.OnKeyDownTrigger) {
  51675. var parameter = action.getTriggerParameter();
  51676. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  51677. if (!parameter.toLowerCase) {
  51678. continue;
  51679. }
  51680. var lowerCase = parameter.toLowerCase();
  51681. if (lowerCase !== evt.sourceEvent.key) {
  51682. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  51683. var actualkey = String.fromCharCode(unicode).toLowerCase();
  51684. if (actualkey !== lowerCase) {
  51685. continue;
  51686. }
  51687. }
  51688. }
  51689. }
  51690. }
  51691. action._executeCurrent(evt);
  51692. }
  51693. }
  51694. };
  51695. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  51696. var properties = propertyPath.split(".");
  51697. for (var index = 0; index < properties.length - 1; index++) {
  51698. target = target[properties[index]];
  51699. }
  51700. return target;
  51701. };
  51702. ActionManager.prototype._getProperty = function (propertyPath) {
  51703. var properties = propertyPath.split(".");
  51704. return properties[properties.length - 1];
  51705. };
  51706. ActionManager.prototype.serialize = function (name) {
  51707. var root = {
  51708. children: new Array(),
  51709. name: name,
  51710. type: 3,
  51711. properties: new Array() // Empty for root but required
  51712. };
  51713. for (var i = 0; i < this.actions.length; i++) {
  51714. var triggerObject = {
  51715. type: 0,
  51716. children: new Array(),
  51717. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  51718. properties: new Array()
  51719. };
  51720. var triggerOptions = this.actions[i].triggerOptions;
  51721. if (triggerOptions && typeof triggerOptions !== "number") {
  51722. if (triggerOptions.parameter instanceof BABYLON.Node) {
  51723. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  51724. }
  51725. else {
  51726. var parameter = {};
  51727. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  51728. if (triggerOptions.parameter.mesh) {
  51729. parameter._meshId = triggerOptions.parameter.mesh.id;
  51730. }
  51731. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  51732. }
  51733. }
  51734. // Serialize child action, recursively
  51735. this.actions[i].serialize(triggerObject);
  51736. // Add serialized trigger
  51737. root.children.push(triggerObject);
  51738. }
  51739. return root;
  51740. };
  51741. ActionManager.Parse = function (parsedActions, object, scene) {
  51742. var actionManager = new ActionManager(scene);
  51743. if (object === null)
  51744. scene.actionManager = actionManager;
  51745. else
  51746. object.actionManager = actionManager;
  51747. // instanciate a new object
  51748. var instanciate = function (name, params) {
  51749. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  51750. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  51751. newInstance.constructor.apply(newInstance, params);
  51752. return newInstance;
  51753. };
  51754. var parseParameter = function (name, value, target, propertyPath) {
  51755. if (propertyPath === null) {
  51756. // String, boolean or float
  51757. var floatValue = parseFloat(value);
  51758. if (value === "true" || value === "false")
  51759. return value === "true";
  51760. else
  51761. return isNaN(floatValue) ? value : floatValue;
  51762. }
  51763. var effectiveTarget = propertyPath.split(".");
  51764. var values = value.split(",");
  51765. // Get effective Target
  51766. for (var i = 0; i < effectiveTarget.length; i++) {
  51767. target = target[effectiveTarget[i]];
  51768. }
  51769. // Return appropriate value with its type
  51770. if (typeof (target) === "boolean")
  51771. return values[0] === "true";
  51772. if (typeof (target) === "string")
  51773. return values[0];
  51774. // Parameters with multiple values such as Vector3 etc.
  51775. var split = new Array();
  51776. for (var i = 0; i < values.length; i++)
  51777. split.push(parseFloat(values[i]));
  51778. if (target instanceof BABYLON.Vector3)
  51779. return BABYLON.Vector3.FromArray(split);
  51780. if (target instanceof BABYLON.Vector4)
  51781. return BABYLON.Vector4.FromArray(split);
  51782. if (target instanceof BABYLON.Color3)
  51783. return BABYLON.Color3.FromArray(split);
  51784. if (target instanceof BABYLON.Color4)
  51785. return BABYLON.Color4.FromArray(split);
  51786. return parseFloat(values[0]);
  51787. };
  51788. // traverse graph per trigger
  51789. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  51790. if (combineArray === void 0) { combineArray = null; }
  51791. if (parsedAction.detached)
  51792. return;
  51793. var parameters = new Array();
  51794. var target = null;
  51795. var propertyPath = null;
  51796. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  51797. // Parameters
  51798. if (parsedAction.type === 2)
  51799. parameters.push(actionManager);
  51800. else
  51801. parameters.push(trigger);
  51802. if (combine) {
  51803. var actions = new Array();
  51804. for (var j = 0; j < parsedAction.combine.length; j++) {
  51805. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  51806. }
  51807. parameters.push(actions);
  51808. }
  51809. else {
  51810. for (var i = 0; i < parsedAction.properties.length; i++) {
  51811. var value = parsedAction.properties[i].value;
  51812. var name = parsedAction.properties[i].name;
  51813. var targetType = parsedAction.properties[i].targetType;
  51814. if (name === "target")
  51815. if (targetType !== null && targetType === "SceneProperties")
  51816. value = target = scene;
  51817. else
  51818. value = target = scene.getNodeByName(value);
  51819. else if (name === "parent")
  51820. value = scene.getNodeByName(value);
  51821. else if (name === "sound")
  51822. value = scene.getSoundByName(value);
  51823. else if (name !== "propertyPath") {
  51824. if (parsedAction.type === 2 && name === "operator")
  51825. value = BABYLON.ValueCondition[value];
  51826. else
  51827. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  51828. }
  51829. else {
  51830. propertyPath = value;
  51831. }
  51832. parameters.push(value);
  51833. }
  51834. }
  51835. if (combineArray === null) {
  51836. parameters.push(condition);
  51837. }
  51838. else {
  51839. parameters.push(null);
  51840. }
  51841. // If interpolate value action
  51842. if (parsedAction.name === "InterpolateValueAction") {
  51843. var param = parameters[parameters.length - 2];
  51844. parameters[parameters.length - 1] = param;
  51845. parameters[parameters.length - 2] = condition;
  51846. }
  51847. // Action or condition(s) and not CombineAction
  51848. var newAction = instanciate(parsedAction.name, parameters);
  51849. if (newAction instanceof BABYLON.Condition && condition !== null) {
  51850. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  51851. if (action)
  51852. action.then(nothing);
  51853. else
  51854. actionManager.registerAction(nothing);
  51855. action = nothing;
  51856. }
  51857. if (combineArray === null) {
  51858. if (newAction instanceof BABYLON.Condition) {
  51859. condition = newAction;
  51860. newAction = action;
  51861. }
  51862. else {
  51863. condition = null;
  51864. if (action)
  51865. action.then(newAction);
  51866. else
  51867. actionManager.registerAction(newAction);
  51868. }
  51869. }
  51870. else {
  51871. combineArray.push(newAction);
  51872. }
  51873. for (var i = 0; i < parsedAction.children.length; i++)
  51874. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  51875. };
  51876. // triggers
  51877. for (var i = 0; i < parsedActions.children.length; i++) {
  51878. var triggerParams;
  51879. var trigger = parsedActions.children[i];
  51880. if (trigger.properties.length > 0) {
  51881. var param = trigger.properties[0].value;
  51882. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  51883. if (value._meshId) {
  51884. value.mesh = scene.getMeshByID(value._meshId);
  51885. }
  51886. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  51887. }
  51888. else
  51889. triggerParams = ActionManager[trigger.name];
  51890. for (var j = 0; j < trigger.children.length; j++) {
  51891. if (!trigger.detached)
  51892. traverse(trigger.children[j], triggerParams, null, null);
  51893. }
  51894. }
  51895. };
  51896. ActionManager.GetTriggerName = function (trigger) {
  51897. switch (trigger) {
  51898. case 0: return "NothingTrigger";
  51899. case 1: return "OnPickTrigger";
  51900. case 2: return "OnLeftPickTrigger";
  51901. case 3: return "OnRightPickTrigger";
  51902. case 4: return "OnCenterPickTrigger";
  51903. case 5: return "OnPickDownTrigger";
  51904. case 6: return "OnPickUpTrigger";
  51905. case 7: return "OnLongPressTrigger";
  51906. case 8: return "OnPointerOverTrigger";
  51907. case 9: return "OnPointerOutTrigger";
  51908. case 10: return "OnEveryFrameTrigger";
  51909. case 11: return "OnIntersectionEnterTrigger";
  51910. case 12: return "OnIntersectionExitTrigger";
  51911. case 13: return "OnKeyDownTrigger";
  51912. case 14: return "OnKeyUpTrigger";
  51913. case 15: return "OnPickOutTrigger";
  51914. default: return "";
  51915. }
  51916. };
  51917. // Statics
  51918. ActionManager._NothingTrigger = 0;
  51919. ActionManager._OnPickTrigger = 1;
  51920. ActionManager._OnLeftPickTrigger = 2;
  51921. ActionManager._OnRightPickTrigger = 3;
  51922. ActionManager._OnCenterPickTrigger = 4;
  51923. ActionManager._OnPickDownTrigger = 5;
  51924. ActionManager._OnDoublePickTrigger = 6;
  51925. ActionManager._OnPickUpTrigger = 7;
  51926. ActionManager._OnLongPressTrigger = 8;
  51927. ActionManager._OnPointerOverTrigger = 9;
  51928. ActionManager._OnPointerOutTrigger = 10;
  51929. ActionManager._OnEveryFrameTrigger = 11;
  51930. ActionManager._OnIntersectionEnterTrigger = 12;
  51931. ActionManager._OnIntersectionExitTrigger = 13;
  51932. ActionManager._OnKeyDownTrigger = 14;
  51933. ActionManager._OnKeyUpTrigger = 15;
  51934. ActionManager._OnPickOutTrigger = 16;
  51935. ActionManager.Triggers = {};
  51936. return ActionManager;
  51937. }());
  51938. BABYLON.ActionManager = ActionManager;
  51939. })(BABYLON || (BABYLON = {}));
  51940. //# sourceMappingURL=babylon.actionManager.js.map
  51941. "use strict";
  51942. var BABYLON;
  51943. (function (BABYLON) {
  51944. var InterpolateValueAction = /** @class */ (function (_super) {
  51945. __extends(InterpolateValueAction, _super);
  51946. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  51947. if (duration === void 0) { duration = 1000; }
  51948. var _this = _super.call(this, triggerOptions, condition) || this;
  51949. _this.propertyPath = propertyPath;
  51950. _this.value = value;
  51951. _this.duration = duration;
  51952. _this.stopOtherAnimations = stopOtherAnimations;
  51953. _this.onInterpolationDone = onInterpolationDone;
  51954. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  51955. _this._target = _this._effectiveTarget = target;
  51956. return _this;
  51957. }
  51958. InterpolateValueAction.prototype._prepare = function () {
  51959. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  51960. this._property = this._getProperty(this.propertyPath);
  51961. };
  51962. InterpolateValueAction.prototype.execute = function () {
  51963. var _this = this;
  51964. var scene = this._actionManager.getScene();
  51965. var keys = [
  51966. {
  51967. frame: 0,
  51968. value: this._effectiveTarget[this._property]
  51969. }, {
  51970. frame: 100,
  51971. value: this.value
  51972. }
  51973. ];
  51974. var dataType;
  51975. if (typeof this.value === "number") {
  51976. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  51977. }
  51978. else if (this.value instanceof BABYLON.Color3) {
  51979. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  51980. }
  51981. else if (this.value instanceof BABYLON.Vector3) {
  51982. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  51983. }
  51984. else if (this.value instanceof BABYLON.Matrix) {
  51985. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  51986. }
  51987. else if (this.value instanceof BABYLON.Quaternion) {
  51988. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  51989. }
  51990. else {
  51991. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  51992. return;
  51993. }
  51994. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  51995. animation.setKeys(keys);
  51996. if (this.stopOtherAnimations) {
  51997. scene.stopAnimation(this._effectiveTarget);
  51998. }
  51999. var wrapper = function () {
  52000. _this.onInterpolationDoneObservable.notifyObservers(_this);
  52001. if (_this.onInterpolationDone) {
  52002. _this.onInterpolationDone();
  52003. }
  52004. };
  52005. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  52006. };
  52007. InterpolateValueAction.prototype.serialize = function (parent) {
  52008. return _super.prototype._serialize.call(this, {
  52009. name: "InterpolateValueAction",
  52010. properties: [
  52011. BABYLON.Action._GetTargetProperty(this._target),
  52012. { name: "propertyPath", value: this.propertyPath },
  52013. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52014. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  52015. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  52016. ]
  52017. }, parent);
  52018. };
  52019. return InterpolateValueAction;
  52020. }(BABYLON.Action));
  52021. BABYLON.InterpolateValueAction = InterpolateValueAction;
  52022. })(BABYLON || (BABYLON = {}));
  52023. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  52024. "use strict";
  52025. var BABYLON;
  52026. (function (BABYLON) {
  52027. var SwitchBooleanAction = /** @class */ (function (_super) {
  52028. __extends(SwitchBooleanAction, _super);
  52029. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  52030. var _this = _super.call(this, triggerOptions, condition) || this;
  52031. _this.propertyPath = propertyPath;
  52032. _this._target = _this._effectiveTarget = target;
  52033. return _this;
  52034. }
  52035. SwitchBooleanAction.prototype._prepare = function () {
  52036. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52037. this._property = this._getProperty(this.propertyPath);
  52038. };
  52039. SwitchBooleanAction.prototype.execute = function () {
  52040. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  52041. };
  52042. SwitchBooleanAction.prototype.serialize = function (parent) {
  52043. return _super.prototype._serialize.call(this, {
  52044. name: "SwitchBooleanAction",
  52045. properties: [
  52046. BABYLON.Action._GetTargetProperty(this._target),
  52047. { name: "propertyPath", value: this.propertyPath }
  52048. ]
  52049. }, parent);
  52050. };
  52051. return SwitchBooleanAction;
  52052. }(BABYLON.Action));
  52053. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  52054. var SetStateAction = /** @class */ (function (_super) {
  52055. __extends(SetStateAction, _super);
  52056. function SetStateAction(triggerOptions, target, value, condition) {
  52057. var _this = _super.call(this, triggerOptions, condition) || this;
  52058. _this.value = value;
  52059. _this._target = target;
  52060. return _this;
  52061. }
  52062. SetStateAction.prototype.execute = function () {
  52063. this._target.state = this.value;
  52064. };
  52065. SetStateAction.prototype.serialize = function (parent) {
  52066. return _super.prototype._serialize.call(this, {
  52067. name: "SetStateAction",
  52068. properties: [
  52069. BABYLON.Action._GetTargetProperty(this._target),
  52070. { name: "value", value: this.value }
  52071. ]
  52072. }, parent);
  52073. };
  52074. return SetStateAction;
  52075. }(BABYLON.Action));
  52076. BABYLON.SetStateAction = SetStateAction;
  52077. var SetValueAction = /** @class */ (function (_super) {
  52078. __extends(SetValueAction, _super);
  52079. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  52080. var _this = _super.call(this, triggerOptions, condition) || this;
  52081. _this.propertyPath = propertyPath;
  52082. _this.value = value;
  52083. _this._target = _this._effectiveTarget = target;
  52084. return _this;
  52085. }
  52086. SetValueAction.prototype._prepare = function () {
  52087. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52088. this._property = this._getProperty(this.propertyPath);
  52089. };
  52090. SetValueAction.prototype.execute = function () {
  52091. this._effectiveTarget[this._property] = this.value;
  52092. if (this._target.markAsDirty) {
  52093. this._target.markAsDirty(this._property);
  52094. }
  52095. };
  52096. SetValueAction.prototype.serialize = function (parent) {
  52097. return _super.prototype._serialize.call(this, {
  52098. name: "SetValueAction",
  52099. properties: [
  52100. BABYLON.Action._GetTargetProperty(this._target),
  52101. { name: "propertyPath", value: this.propertyPath },
  52102. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  52103. ]
  52104. }, parent);
  52105. };
  52106. return SetValueAction;
  52107. }(BABYLON.Action));
  52108. BABYLON.SetValueAction = SetValueAction;
  52109. var IncrementValueAction = /** @class */ (function (_super) {
  52110. __extends(IncrementValueAction, _super);
  52111. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  52112. var _this = _super.call(this, triggerOptions, condition) || this;
  52113. _this.propertyPath = propertyPath;
  52114. _this.value = value;
  52115. _this._target = _this._effectiveTarget = target;
  52116. return _this;
  52117. }
  52118. IncrementValueAction.prototype._prepare = function () {
  52119. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52120. this._property = this._getProperty(this.propertyPath);
  52121. if (typeof this._effectiveTarget[this._property] !== "number") {
  52122. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  52123. }
  52124. };
  52125. IncrementValueAction.prototype.execute = function () {
  52126. this._effectiveTarget[this._property] += this.value;
  52127. if (this._target.markAsDirty) {
  52128. this._target.markAsDirty(this._property);
  52129. }
  52130. };
  52131. IncrementValueAction.prototype.serialize = function (parent) {
  52132. return _super.prototype._serialize.call(this, {
  52133. name: "IncrementValueAction",
  52134. properties: [
  52135. BABYLON.Action._GetTargetProperty(this._target),
  52136. { name: "propertyPath", value: this.propertyPath },
  52137. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  52138. ]
  52139. }, parent);
  52140. };
  52141. return IncrementValueAction;
  52142. }(BABYLON.Action));
  52143. BABYLON.IncrementValueAction = IncrementValueAction;
  52144. var PlayAnimationAction = /** @class */ (function (_super) {
  52145. __extends(PlayAnimationAction, _super);
  52146. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  52147. var _this = _super.call(this, triggerOptions, condition) || this;
  52148. _this.from = from;
  52149. _this.to = to;
  52150. _this.loop = loop;
  52151. _this._target = target;
  52152. return _this;
  52153. }
  52154. PlayAnimationAction.prototype._prepare = function () {
  52155. };
  52156. PlayAnimationAction.prototype.execute = function () {
  52157. var scene = this._actionManager.getScene();
  52158. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  52159. };
  52160. PlayAnimationAction.prototype.serialize = function (parent) {
  52161. return _super.prototype._serialize.call(this, {
  52162. name: "PlayAnimationAction",
  52163. properties: [
  52164. BABYLON.Action._GetTargetProperty(this._target),
  52165. { name: "from", value: String(this.from) },
  52166. { name: "to", value: String(this.to) },
  52167. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  52168. ]
  52169. }, parent);
  52170. };
  52171. return PlayAnimationAction;
  52172. }(BABYLON.Action));
  52173. BABYLON.PlayAnimationAction = PlayAnimationAction;
  52174. var StopAnimationAction = /** @class */ (function (_super) {
  52175. __extends(StopAnimationAction, _super);
  52176. function StopAnimationAction(triggerOptions, target, condition) {
  52177. var _this = _super.call(this, triggerOptions, condition) || this;
  52178. _this._target = target;
  52179. return _this;
  52180. }
  52181. StopAnimationAction.prototype._prepare = function () {
  52182. };
  52183. StopAnimationAction.prototype.execute = function () {
  52184. var scene = this._actionManager.getScene();
  52185. scene.stopAnimation(this._target);
  52186. };
  52187. StopAnimationAction.prototype.serialize = function (parent) {
  52188. return _super.prototype._serialize.call(this, {
  52189. name: "StopAnimationAction",
  52190. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  52191. }, parent);
  52192. };
  52193. return StopAnimationAction;
  52194. }(BABYLON.Action));
  52195. BABYLON.StopAnimationAction = StopAnimationAction;
  52196. var DoNothingAction = /** @class */ (function (_super) {
  52197. __extends(DoNothingAction, _super);
  52198. function DoNothingAction(triggerOptions, condition) {
  52199. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  52200. return _super.call(this, triggerOptions, condition) || this;
  52201. }
  52202. DoNothingAction.prototype.execute = function () {
  52203. };
  52204. DoNothingAction.prototype.serialize = function (parent) {
  52205. return _super.prototype._serialize.call(this, {
  52206. name: "DoNothingAction",
  52207. properties: []
  52208. }, parent);
  52209. };
  52210. return DoNothingAction;
  52211. }(BABYLON.Action));
  52212. BABYLON.DoNothingAction = DoNothingAction;
  52213. var CombineAction = /** @class */ (function (_super) {
  52214. __extends(CombineAction, _super);
  52215. function CombineAction(triggerOptions, children, condition) {
  52216. var _this = _super.call(this, triggerOptions, condition) || this;
  52217. _this.children = children;
  52218. return _this;
  52219. }
  52220. CombineAction.prototype._prepare = function () {
  52221. for (var index = 0; index < this.children.length; index++) {
  52222. this.children[index]._actionManager = this._actionManager;
  52223. this.children[index]._prepare();
  52224. }
  52225. };
  52226. CombineAction.prototype.execute = function (evt) {
  52227. for (var index = 0; index < this.children.length; index++) {
  52228. this.children[index].execute(evt);
  52229. }
  52230. };
  52231. CombineAction.prototype.serialize = function (parent) {
  52232. var serializationObject = _super.prototype._serialize.call(this, {
  52233. name: "CombineAction",
  52234. properties: [],
  52235. combine: []
  52236. }, parent);
  52237. for (var i = 0; i < this.children.length; i++) {
  52238. serializationObject.combine.push(this.children[i].serialize(null));
  52239. }
  52240. return serializationObject;
  52241. };
  52242. return CombineAction;
  52243. }(BABYLON.Action));
  52244. BABYLON.CombineAction = CombineAction;
  52245. var ExecuteCodeAction = /** @class */ (function (_super) {
  52246. __extends(ExecuteCodeAction, _super);
  52247. function ExecuteCodeAction(triggerOptions, func, condition) {
  52248. var _this = _super.call(this, triggerOptions, condition) || this;
  52249. _this.func = func;
  52250. return _this;
  52251. }
  52252. ExecuteCodeAction.prototype.execute = function (evt) {
  52253. this.func(evt);
  52254. };
  52255. return ExecuteCodeAction;
  52256. }(BABYLON.Action));
  52257. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  52258. var SetParentAction = /** @class */ (function (_super) {
  52259. __extends(SetParentAction, _super);
  52260. function SetParentAction(triggerOptions, target, parent, condition) {
  52261. var _this = _super.call(this, triggerOptions, condition) || this;
  52262. _this._target = target;
  52263. _this._parent = parent;
  52264. return _this;
  52265. }
  52266. SetParentAction.prototype._prepare = function () {
  52267. };
  52268. SetParentAction.prototype.execute = function () {
  52269. if (this._target.parent === this._parent) {
  52270. return;
  52271. }
  52272. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  52273. invertParentWorldMatrix.invert();
  52274. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  52275. this._target.parent = this._parent;
  52276. };
  52277. SetParentAction.prototype.serialize = function (parent) {
  52278. return _super.prototype._serialize.call(this, {
  52279. name: "SetParentAction",
  52280. properties: [
  52281. BABYLON.Action._GetTargetProperty(this._target),
  52282. BABYLON.Action._GetTargetProperty(this._parent),
  52283. ]
  52284. }, parent);
  52285. };
  52286. return SetParentAction;
  52287. }(BABYLON.Action));
  52288. BABYLON.SetParentAction = SetParentAction;
  52289. var PlaySoundAction = /** @class */ (function (_super) {
  52290. __extends(PlaySoundAction, _super);
  52291. function PlaySoundAction(triggerOptions, sound, condition) {
  52292. var _this = _super.call(this, triggerOptions, condition) || this;
  52293. _this._sound = sound;
  52294. return _this;
  52295. }
  52296. PlaySoundAction.prototype._prepare = function () {
  52297. };
  52298. PlaySoundAction.prototype.execute = function () {
  52299. if (this._sound !== undefined)
  52300. this._sound.play();
  52301. };
  52302. PlaySoundAction.prototype.serialize = function (parent) {
  52303. return _super.prototype._serialize.call(this, {
  52304. name: "PlaySoundAction",
  52305. properties: [{ name: "sound", value: this._sound.name }]
  52306. }, parent);
  52307. };
  52308. return PlaySoundAction;
  52309. }(BABYLON.Action));
  52310. BABYLON.PlaySoundAction = PlaySoundAction;
  52311. var StopSoundAction = /** @class */ (function (_super) {
  52312. __extends(StopSoundAction, _super);
  52313. function StopSoundAction(triggerOptions, sound, condition) {
  52314. var _this = _super.call(this, triggerOptions, condition) || this;
  52315. _this._sound = sound;
  52316. return _this;
  52317. }
  52318. StopSoundAction.prototype._prepare = function () {
  52319. };
  52320. StopSoundAction.prototype.execute = function () {
  52321. if (this._sound !== undefined)
  52322. this._sound.stop();
  52323. };
  52324. StopSoundAction.prototype.serialize = function (parent) {
  52325. return _super.prototype._serialize.call(this, {
  52326. name: "StopSoundAction",
  52327. properties: [{ name: "sound", value: this._sound.name }]
  52328. }, parent);
  52329. };
  52330. return StopSoundAction;
  52331. }(BABYLON.Action));
  52332. BABYLON.StopSoundAction = StopSoundAction;
  52333. })(BABYLON || (BABYLON = {}));
  52334. //# sourceMappingURL=babylon.directActions.js.map
  52335. "use strict";
  52336. var BABYLON;
  52337. (function (BABYLON) {
  52338. var SpriteManager = /** @class */ (function () {
  52339. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  52340. if (epsilon === void 0) { epsilon = 0.01; }
  52341. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52342. this.name = name;
  52343. this.sprites = new Array();
  52344. this.renderingGroupId = 0;
  52345. this.layerMask = 0x0FFFFFFF;
  52346. this.fogEnabled = true;
  52347. this.isPickable = false;
  52348. /**
  52349. * An event triggered when the manager is disposed.
  52350. */
  52351. this.onDisposeObservable = new BABYLON.Observable();
  52352. this._vertexBuffers = {};
  52353. this._capacity = capacity;
  52354. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  52355. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52356. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52357. if (cellSize.width && cellSize.height) {
  52358. this.cellWidth = cellSize.width;
  52359. this.cellHeight = cellSize.height;
  52360. }
  52361. else if (cellSize !== undefined) {
  52362. this.cellWidth = cellSize;
  52363. this.cellHeight = cellSize;
  52364. }
  52365. else {
  52366. return;
  52367. }
  52368. this._epsilon = epsilon;
  52369. this._scene = scene;
  52370. this._scene.spriteManagers.push(this);
  52371. var indices = [];
  52372. var index = 0;
  52373. for (var count = 0; count < capacity; count++) {
  52374. indices.push(index);
  52375. indices.push(index + 1);
  52376. indices.push(index + 2);
  52377. indices.push(index);
  52378. indices.push(index + 2);
  52379. indices.push(index + 3);
  52380. index += 4;
  52381. }
  52382. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  52383. // VBO
  52384. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  52385. this._vertexData = new Float32Array(capacity * 16 * 4);
  52386. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  52387. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  52388. var options = this._buffer.createVertexBuffer("options", 4, 4);
  52389. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  52390. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  52391. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  52392. this._vertexBuffers["options"] = options;
  52393. this._vertexBuffers["cellInfo"] = cellInfo;
  52394. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  52395. // Effects
  52396. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  52397. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  52398. }
  52399. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  52400. set: function (callback) {
  52401. if (this._onDisposeObserver) {
  52402. this.onDisposeObservable.remove(this._onDisposeObserver);
  52403. }
  52404. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  52405. },
  52406. enumerable: true,
  52407. configurable: true
  52408. });
  52409. Object.defineProperty(SpriteManager.prototype, "texture", {
  52410. get: function () {
  52411. return this._spriteTexture;
  52412. },
  52413. set: function (value) {
  52414. this._spriteTexture = value;
  52415. },
  52416. enumerable: true,
  52417. configurable: true
  52418. });
  52419. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  52420. var arrayOffset = index * 16;
  52421. if (offsetX === 0)
  52422. offsetX = this._epsilon;
  52423. else if (offsetX === 1)
  52424. offsetX = 1 - this._epsilon;
  52425. if (offsetY === 0)
  52426. offsetY = this._epsilon;
  52427. else if (offsetY === 1)
  52428. offsetY = 1 - this._epsilon;
  52429. this._vertexData[arrayOffset] = sprite.position.x;
  52430. this._vertexData[arrayOffset + 1] = sprite.position.y;
  52431. this._vertexData[arrayOffset + 2] = sprite.position.z;
  52432. this._vertexData[arrayOffset + 3] = sprite.angle;
  52433. this._vertexData[arrayOffset + 4] = sprite.width;
  52434. this._vertexData[arrayOffset + 5] = sprite.height;
  52435. this._vertexData[arrayOffset + 6] = offsetX;
  52436. this._vertexData[arrayOffset + 7] = offsetY;
  52437. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  52438. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  52439. var offset = (sprite.cellIndex / rowSize) >> 0;
  52440. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  52441. this._vertexData[arrayOffset + 11] = offset;
  52442. // Color
  52443. this._vertexData[arrayOffset + 12] = sprite.color.r;
  52444. this._vertexData[arrayOffset + 13] = sprite.color.g;
  52445. this._vertexData[arrayOffset + 14] = sprite.color.b;
  52446. this._vertexData[arrayOffset + 15] = sprite.color.a;
  52447. };
  52448. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  52449. var count = Math.min(this._capacity, this.sprites.length);
  52450. var min = BABYLON.Vector3.Zero();
  52451. var max = BABYLON.Vector3.Zero();
  52452. var distance = Number.MAX_VALUE;
  52453. var currentSprite = null;
  52454. var cameraSpacePosition = BABYLON.Vector3.Zero();
  52455. var cameraView = camera.getViewMatrix();
  52456. for (var index = 0; index < count; index++) {
  52457. var sprite = this.sprites[index];
  52458. if (!sprite) {
  52459. continue;
  52460. }
  52461. if (predicate) {
  52462. if (!predicate(sprite)) {
  52463. continue;
  52464. }
  52465. }
  52466. else if (!sprite.isPickable) {
  52467. continue;
  52468. }
  52469. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  52470. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  52471. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  52472. if (ray.intersectsBoxMinMax(min, max)) {
  52473. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  52474. if (distance > currentDistance) {
  52475. distance = currentDistance;
  52476. currentSprite = sprite;
  52477. if (fastCheck) {
  52478. break;
  52479. }
  52480. }
  52481. }
  52482. }
  52483. if (currentSprite) {
  52484. var result = new BABYLON.PickingInfo();
  52485. result.hit = true;
  52486. result.pickedSprite = currentSprite;
  52487. result.distance = distance;
  52488. return result;
  52489. }
  52490. return null;
  52491. };
  52492. SpriteManager.prototype.render = function () {
  52493. // Check
  52494. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  52495. return;
  52496. var engine = this._scene.getEngine();
  52497. var baseSize = this._spriteTexture.getBaseSize();
  52498. // Sprites
  52499. var deltaTime = engine.getDeltaTime();
  52500. var max = Math.min(this._capacity, this.sprites.length);
  52501. var rowSize = baseSize.width / this.cellWidth;
  52502. var offset = 0;
  52503. for (var index = 0; index < max; index++) {
  52504. var sprite = this.sprites[index];
  52505. if (!sprite) {
  52506. continue;
  52507. }
  52508. sprite._animate(deltaTime);
  52509. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  52510. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  52511. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  52512. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  52513. }
  52514. this._buffer.update(this._vertexData);
  52515. // Render
  52516. var effect = this._effectBase;
  52517. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  52518. effect = this._effectFog;
  52519. }
  52520. engine.enableEffect(effect);
  52521. var viewMatrix = this._scene.getViewMatrix();
  52522. effect.setTexture("diffuseSampler", this._spriteTexture);
  52523. effect.setMatrix("view", viewMatrix);
  52524. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  52525. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  52526. // Fog
  52527. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  52528. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  52529. effect.setColor3("vFogColor", this._scene.fogColor);
  52530. }
  52531. // VBOs
  52532. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  52533. // Draw order
  52534. engine.setDepthFunctionToLessOrEqual();
  52535. effect.setBool("alphaTest", true);
  52536. engine.setColorWrite(false);
  52537. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  52538. engine.setColorWrite(true);
  52539. effect.setBool("alphaTest", false);
  52540. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  52541. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  52542. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  52543. };
  52544. SpriteManager.prototype.dispose = function () {
  52545. if (this._buffer) {
  52546. this._buffer.dispose();
  52547. this._buffer = null;
  52548. }
  52549. if (this._indexBuffer) {
  52550. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  52551. this._indexBuffer = null;
  52552. }
  52553. if (this._spriteTexture) {
  52554. this._spriteTexture.dispose();
  52555. this._spriteTexture = null;
  52556. }
  52557. // Remove from scene
  52558. var index = this._scene.spriteManagers.indexOf(this);
  52559. this._scene.spriteManagers.splice(index, 1);
  52560. // Callback
  52561. this.onDisposeObservable.notifyObservers(this);
  52562. this.onDisposeObservable.clear();
  52563. };
  52564. return SpriteManager;
  52565. }());
  52566. BABYLON.SpriteManager = SpriteManager;
  52567. })(BABYLON || (BABYLON = {}));
  52568. //# sourceMappingURL=babylon.spriteManager.js.map
  52569. "use strict";
  52570. var BABYLON;
  52571. (function (BABYLON) {
  52572. var Sprite = /** @class */ (function () {
  52573. function Sprite(name, manager) {
  52574. this.name = name;
  52575. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52576. this.width = 1.0;
  52577. this.height = 1.0;
  52578. this.angle = 0;
  52579. this.cellIndex = 0;
  52580. this.invertU = 0;
  52581. this.invertV = 0;
  52582. this.animations = new Array();
  52583. this.isPickable = false;
  52584. this._animationStarted = false;
  52585. this._loopAnimation = false;
  52586. this._fromIndex = 0;
  52587. this._toIndex = 0;
  52588. this._delay = 0;
  52589. this._direction = 1;
  52590. this._time = 0;
  52591. this._manager = manager;
  52592. this._manager.sprites.push(this);
  52593. this.position = BABYLON.Vector3.Zero();
  52594. }
  52595. Object.defineProperty(Sprite.prototype, "size", {
  52596. get: function () {
  52597. return this.width;
  52598. },
  52599. set: function (value) {
  52600. this.width = value;
  52601. this.height = value;
  52602. },
  52603. enumerable: true,
  52604. configurable: true
  52605. });
  52606. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  52607. this._fromIndex = from;
  52608. this._toIndex = to;
  52609. this._loopAnimation = loop;
  52610. this._delay = delay;
  52611. this._animationStarted = true;
  52612. this._direction = from < to ? 1 : -1;
  52613. this.cellIndex = from;
  52614. this._time = 0;
  52615. this._onAnimationEnd = onAnimationEnd;
  52616. };
  52617. Sprite.prototype.stopAnimation = function () {
  52618. this._animationStarted = false;
  52619. };
  52620. Sprite.prototype._animate = function (deltaTime) {
  52621. if (!this._animationStarted)
  52622. return;
  52623. this._time += deltaTime;
  52624. if (this._time > this._delay) {
  52625. this._time = this._time % this._delay;
  52626. this.cellIndex += this._direction;
  52627. if (this.cellIndex > this._toIndex) {
  52628. if (this._loopAnimation) {
  52629. this.cellIndex = this._fromIndex;
  52630. }
  52631. else {
  52632. this.cellIndex = this._toIndex;
  52633. this._animationStarted = false;
  52634. if (this._onAnimationEnd) {
  52635. this._onAnimationEnd();
  52636. }
  52637. if (this.disposeWhenFinishedAnimating) {
  52638. this.dispose();
  52639. }
  52640. }
  52641. }
  52642. }
  52643. };
  52644. Sprite.prototype.dispose = function () {
  52645. for (var i = 0; i < this._manager.sprites.length; i++) {
  52646. if (this._manager.sprites[i] == this) {
  52647. this._manager.sprites.splice(i, 1);
  52648. }
  52649. }
  52650. };
  52651. return Sprite;
  52652. }());
  52653. BABYLON.Sprite = Sprite;
  52654. })(BABYLON || (BABYLON = {}));
  52655. //# sourceMappingURL=babylon.sprite.js.map
  52656. "use strict";
  52657. var BABYLON;
  52658. (function (BABYLON) {
  52659. var IntersectionInfo = /** @class */ (function () {
  52660. function IntersectionInfo(bu, bv, distance) {
  52661. this.bu = bu;
  52662. this.bv = bv;
  52663. this.distance = distance;
  52664. this.faceId = 0;
  52665. this.subMeshId = 0;
  52666. }
  52667. return IntersectionInfo;
  52668. }());
  52669. BABYLON.IntersectionInfo = IntersectionInfo;
  52670. var PickingInfo = /** @class */ (function () {
  52671. function PickingInfo() {
  52672. this.hit = false;
  52673. this.distance = 0;
  52674. this.pickedPoint = null;
  52675. this.pickedMesh = null;
  52676. this.bu = 0;
  52677. this.bv = 0;
  52678. this.faceId = -1;
  52679. this.subMeshId = 0;
  52680. this.pickedSprite = null;
  52681. }
  52682. // Methods
  52683. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  52684. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  52685. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  52686. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  52687. return null;
  52688. }
  52689. var indices = this.pickedMesh.getIndices();
  52690. if (!indices) {
  52691. return null;
  52692. }
  52693. var result;
  52694. if (useVerticesNormals) {
  52695. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52696. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  52697. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  52698. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  52699. normal0 = normal0.scale(this.bu);
  52700. normal1 = normal1.scale(this.bv);
  52701. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  52702. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  52703. }
  52704. else {
  52705. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52706. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  52707. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  52708. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  52709. var p1p2 = vertex1.subtract(vertex2);
  52710. var p3p2 = vertex3.subtract(vertex2);
  52711. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  52712. }
  52713. if (useWorldCoordinates) {
  52714. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  52715. }
  52716. return BABYLON.Vector3.Normalize(result);
  52717. };
  52718. PickingInfo.prototype.getTextureCoordinates = function () {
  52719. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  52720. return null;
  52721. }
  52722. var indices = this.pickedMesh.getIndices();
  52723. if (!indices) {
  52724. return null;
  52725. }
  52726. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52727. if (!uvs) {
  52728. return null;
  52729. }
  52730. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  52731. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  52732. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  52733. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  52734. uv1 = uv1.scale(this.bu);
  52735. uv2 = uv2.scale(this.bv);
  52736. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  52737. };
  52738. return PickingInfo;
  52739. }());
  52740. BABYLON.PickingInfo = PickingInfo;
  52741. })(BABYLON || (BABYLON = {}));
  52742. //# sourceMappingURL=babylon.pickingInfo.js.map
  52743. "use strict";
  52744. var BABYLON;
  52745. (function (BABYLON) {
  52746. var Ray = /** @class */ (function () {
  52747. function Ray(origin, direction, length) {
  52748. if (length === void 0) { length = Number.MAX_VALUE; }
  52749. this.origin = origin;
  52750. this.direction = direction;
  52751. this.length = length;
  52752. }
  52753. // Methods
  52754. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  52755. var d = 0.0;
  52756. var maxValue = Number.MAX_VALUE;
  52757. var inv;
  52758. var min;
  52759. var max;
  52760. var temp;
  52761. if (Math.abs(this.direction.x) < 0.0000001) {
  52762. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  52763. return false;
  52764. }
  52765. }
  52766. else {
  52767. inv = 1.0 / this.direction.x;
  52768. min = (minimum.x - this.origin.x) * inv;
  52769. max = (maximum.x - this.origin.x) * inv;
  52770. if (max === -Infinity) {
  52771. max = Infinity;
  52772. }
  52773. if (min > max) {
  52774. temp = min;
  52775. min = max;
  52776. max = temp;
  52777. }
  52778. d = Math.max(min, d);
  52779. maxValue = Math.min(max, maxValue);
  52780. if (d > maxValue) {
  52781. return false;
  52782. }
  52783. }
  52784. if (Math.abs(this.direction.y) < 0.0000001) {
  52785. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  52786. return false;
  52787. }
  52788. }
  52789. else {
  52790. inv = 1.0 / this.direction.y;
  52791. min = (minimum.y - this.origin.y) * inv;
  52792. max = (maximum.y - this.origin.y) * inv;
  52793. if (max === -Infinity) {
  52794. max = Infinity;
  52795. }
  52796. if (min > max) {
  52797. temp = min;
  52798. min = max;
  52799. max = temp;
  52800. }
  52801. d = Math.max(min, d);
  52802. maxValue = Math.min(max, maxValue);
  52803. if (d > maxValue) {
  52804. return false;
  52805. }
  52806. }
  52807. if (Math.abs(this.direction.z) < 0.0000001) {
  52808. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  52809. return false;
  52810. }
  52811. }
  52812. else {
  52813. inv = 1.0 / this.direction.z;
  52814. min = (minimum.z - this.origin.z) * inv;
  52815. max = (maximum.z - this.origin.z) * inv;
  52816. if (max === -Infinity) {
  52817. max = Infinity;
  52818. }
  52819. if (min > max) {
  52820. temp = min;
  52821. min = max;
  52822. max = temp;
  52823. }
  52824. d = Math.max(min, d);
  52825. maxValue = Math.min(max, maxValue);
  52826. if (d > maxValue) {
  52827. return false;
  52828. }
  52829. }
  52830. return true;
  52831. };
  52832. Ray.prototype.intersectsBox = function (box) {
  52833. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  52834. };
  52835. Ray.prototype.intersectsSphere = function (sphere) {
  52836. var x = sphere.center.x - this.origin.x;
  52837. var y = sphere.center.y - this.origin.y;
  52838. var z = sphere.center.z - this.origin.z;
  52839. var pyth = (x * x) + (y * y) + (z * z);
  52840. var rr = sphere.radius * sphere.radius;
  52841. if (pyth <= rr) {
  52842. return true;
  52843. }
  52844. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  52845. if (dot < 0.0) {
  52846. return false;
  52847. }
  52848. var temp = pyth - (dot * dot);
  52849. return temp <= rr;
  52850. };
  52851. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  52852. if (!this._edge1) {
  52853. this._edge1 = BABYLON.Vector3.Zero();
  52854. this._edge2 = BABYLON.Vector3.Zero();
  52855. this._pvec = BABYLON.Vector3.Zero();
  52856. this._tvec = BABYLON.Vector3.Zero();
  52857. this._qvec = BABYLON.Vector3.Zero();
  52858. }
  52859. vertex1.subtractToRef(vertex0, this._edge1);
  52860. vertex2.subtractToRef(vertex0, this._edge2);
  52861. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  52862. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  52863. if (det === 0) {
  52864. return null;
  52865. }
  52866. var invdet = 1 / det;
  52867. this.origin.subtractToRef(vertex0, this._tvec);
  52868. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  52869. if (bu < 0 || bu > 1.0) {
  52870. return null;
  52871. }
  52872. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  52873. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  52874. if (bv < 0 || bu + bv > 1.0) {
  52875. return null;
  52876. }
  52877. //check if the distance is longer than the predefined length.
  52878. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  52879. if (distance > this.length) {
  52880. return null;
  52881. }
  52882. return new BABYLON.IntersectionInfo(bu, bv, distance);
  52883. };
  52884. Ray.prototype.intersectsPlane = function (plane) {
  52885. var distance;
  52886. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  52887. if (Math.abs(result1) < 9.99999997475243E-07) {
  52888. return null;
  52889. }
  52890. else {
  52891. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  52892. distance = (-plane.d - result2) / result1;
  52893. if (distance < 0.0) {
  52894. if (distance < -9.99999997475243E-07) {
  52895. return null;
  52896. }
  52897. else {
  52898. return 0;
  52899. }
  52900. }
  52901. return distance;
  52902. }
  52903. };
  52904. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  52905. var tm = BABYLON.Tmp.Matrix[0];
  52906. mesh.getWorldMatrix().invertToRef(tm);
  52907. if (this._tmpRay) {
  52908. Ray.TransformToRef(this, tm, this._tmpRay);
  52909. }
  52910. else {
  52911. this._tmpRay = Ray.Transform(this, tm);
  52912. }
  52913. return mesh.intersects(this._tmpRay, fastCheck);
  52914. };
  52915. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  52916. if (results) {
  52917. results.length = 0;
  52918. }
  52919. else {
  52920. results = [];
  52921. }
  52922. for (var i = 0; i < meshes.length; i++) {
  52923. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  52924. if (pickInfo.hit) {
  52925. results.push(pickInfo);
  52926. }
  52927. }
  52928. results.sort(this._comparePickingInfo);
  52929. return results;
  52930. };
  52931. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  52932. if (pickingInfoA.distance < pickingInfoB.distance) {
  52933. return -1;
  52934. }
  52935. else if (pickingInfoA.distance > pickingInfoB.distance) {
  52936. return 1;
  52937. }
  52938. else {
  52939. return 0;
  52940. }
  52941. };
  52942. /**
  52943. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  52944. * @param sega the first point of the segment to test the intersection against
  52945. * @param segb the second point of the segment to test the intersection against
  52946. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  52947. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  52948. */
  52949. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  52950. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  52951. var u = segb.subtract(sega);
  52952. var v = rsegb.subtract(this.origin);
  52953. var w = sega.subtract(this.origin);
  52954. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  52955. var b = BABYLON.Vector3.Dot(u, v);
  52956. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  52957. var d = BABYLON.Vector3.Dot(u, w);
  52958. var e = BABYLON.Vector3.Dot(v, w);
  52959. var D = a * c - b * b; // always >= 0
  52960. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  52961. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  52962. // compute the line parameters of the two closest points
  52963. if (D < Ray.smallnum) {
  52964. sN = 0.0; // force using point P0 on segment S1
  52965. sD = 1.0; // to prevent possible division by 0.0 later
  52966. tN = e;
  52967. tD = c;
  52968. }
  52969. else {
  52970. sN = (b * e - c * d);
  52971. tN = (a * e - b * d);
  52972. if (sN < 0.0) {
  52973. sN = 0.0;
  52974. tN = e;
  52975. tD = c;
  52976. }
  52977. else if (sN > sD) {
  52978. sN = sD;
  52979. tN = e + b;
  52980. tD = c;
  52981. }
  52982. }
  52983. if (tN < 0.0) {
  52984. tN = 0.0;
  52985. // recompute sc for this edge
  52986. if (-d < 0.0) {
  52987. sN = 0.0;
  52988. }
  52989. else if (-d > a)
  52990. sN = sD;
  52991. else {
  52992. sN = -d;
  52993. sD = a;
  52994. }
  52995. }
  52996. else if (tN > tD) {
  52997. tN = tD;
  52998. // recompute sc for this edge
  52999. if ((-d + b) < 0.0) {
  53000. sN = 0;
  53001. }
  53002. else if ((-d + b) > a) {
  53003. sN = sD;
  53004. }
  53005. else {
  53006. sN = (-d + b);
  53007. sD = a;
  53008. }
  53009. }
  53010. // finally do the division to get sc and tc
  53011. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  53012. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  53013. // get the difference of the two closest points
  53014. var qtc = v.multiplyByFloats(tc, tc, tc);
  53015. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  53016. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  53017. if (isIntersected) {
  53018. return qtc.length();
  53019. }
  53020. return -1;
  53021. };
  53022. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  53023. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  53024. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  53025. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  53026. this.direction.normalize();
  53027. return this;
  53028. };
  53029. // Statics
  53030. Ray.Zero = function () {
  53031. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  53032. };
  53033. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  53034. var result = Ray.Zero();
  53035. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  53036. };
  53037. /**
  53038. * 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
  53039. * transformed to the given world matrix.
  53040. * @param origin The origin point
  53041. * @param end The end point
  53042. * @param world a matrix to transform the ray to. Default is the identity matrix.
  53043. */
  53044. Ray.CreateNewFromTo = function (origin, end, world) {
  53045. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  53046. var direction = end.subtract(origin);
  53047. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  53048. direction.normalize();
  53049. return Ray.Transform(new Ray(origin, direction, length), world);
  53050. };
  53051. Ray.Transform = function (ray, matrix) {
  53052. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  53053. Ray.TransformToRef(ray, matrix, result);
  53054. return result;
  53055. };
  53056. Ray.TransformToRef = function (ray, matrix, result) {
  53057. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  53058. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  53059. result.length = ray.length;
  53060. var dir = result.direction;
  53061. var len = dir.length();
  53062. if (!(len === 0 || len === 1)) {
  53063. var num = 1.0 / len;
  53064. dir.x *= num;
  53065. dir.y *= num;
  53066. dir.z *= num;
  53067. result.length *= len;
  53068. }
  53069. };
  53070. Ray.smallnum = 0.00000001;
  53071. Ray.rayl = 10e8;
  53072. return Ray;
  53073. }());
  53074. BABYLON.Ray = Ray;
  53075. })(BABYLON || (BABYLON = {}));
  53076. //# sourceMappingURL=babylon.ray.js.map
  53077. "use strict";
  53078. var BABYLON;
  53079. (function (BABYLON) {
  53080. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  53081. if (boxMin.x > sphereCenter.x + sphereRadius)
  53082. return false;
  53083. if (sphereCenter.x - sphereRadius > boxMax.x)
  53084. return false;
  53085. if (boxMin.y > sphereCenter.y + sphereRadius)
  53086. return false;
  53087. if (sphereCenter.y - sphereRadius > boxMax.y)
  53088. return false;
  53089. if (boxMin.z > sphereCenter.z + sphereRadius)
  53090. return false;
  53091. if (sphereCenter.z - sphereRadius > boxMax.z)
  53092. return false;
  53093. return true;
  53094. };
  53095. var getLowestRoot = (function () {
  53096. var result = { root: 0, found: false };
  53097. return function (a, b, c, maxR) {
  53098. result.root = 0;
  53099. result.found = false;
  53100. var determinant = b * b - 4.0 * a * c;
  53101. if (determinant < 0)
  53102. return result;
  53103. var sqrtD = Math.sqrt(determinant);
  53104. var r1 = (-b - sqrtD) / (2.0 * a);
  53105. var r2 = (-b + sqrtD) / (2.0 * a);
  53106. if (r1 > r2) {
  53107. var temp = r2;
  53108. r2 = r1;
  53109. r1 = temp;
  53110. }
  53111. if (r1 > 0 && r1 < maxR) {
  53112. result.root = r1;
  53113. result.found = true;
  53114. return result;
  53115. }
  53116. if (r2 > 0 && r2 < maxR) {
  53117. result.root = r2;
  53118. result.found = true;
  53119. return result;
  53120. }
  53121. return result;
  53122. };
  53123. })();
  53124. var Collider = /** @class */ (function () {
  53125. function Collider() {
  53126. this._collisionPoint = BABYLON.Vector3.Zero();
  53127. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  53128. this._tempVector = BABYLON.Vector3.Zero();
  53129. this._tempVector2 = BABYLON.Vector3.Zero();
  53130. this._tempVector3 = BABYLON.Vector3.Zero();
  53131. this._tempVector4 = BABYLON.Vector3.Zero();
  53132. this._edge = BABYLON.Vector3.Zero();
  53133. this._baseToVertex = BABYLON.Vector3.Zero();
  53134. this._destinationPoint = BABYLON.Vector3.Zero();
  53135. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  53136. this._displacementVector = BABYLON.Vector3.Zero();
  53137. this._radius = BABYLON.Vector3.One();
  53138. this._retry = 0;
  53139. this._basePointWorld = BABYLON.Vector3.Zero();
  53140. this._velocityWorld = BABYLON.Vector3.Zero();
  53141. this._normalizedVelocity = BABYLON.Vector3.Zero();
  53142. this._collisionMask = -1;
  53143. }
  53144. Object.defineProperty(Collider.prototype, "collisionMask", {
  53145. get: function () {
  53146. return this._collisionMask;
  53147. },
  53148. set: function (mask) {
  53149. this._collisionMask = !isNaN(mask) ? mask : -1;
  53150. },
  53151. enumerable: true,
  53152. configurable: true
  53153. });
  53154. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  53155. /**
  53156. * Gets the plane normal used to compute the sliding response (in local space)
  53157. */
  53158. get: function () {
  53159. return this._slidePlaneNormal;
  53160. },
  53161. enumerable: true,
  53162. configurable: true
  53163. });
  53164. // Methods
  53165. Collider.prototype._initialize = function (source, dir, e) {
  53166. this._velocity = dir;
  53167. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  53168. this._basePoint = source;
  53169. source.multiplyToRef(this._radius, this._basePointWorld);
  53170. dir.multiplyToRef(this._radius, this._velocityWorld);
  53171. this._velocityWorldLength = this._velocityWorld.length();
  53172. this._epsilon = e;
  53173. this.collisionFound = false;
  53174. };
  53175. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  53176. pa.subtractToRef(point, this._tempVector);
  53177. pb.subtractToRef(point, this._tempVector2);
  53178. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  53179. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  53180. if (d < 0)
  53181. return false;
  53182. pc.subtractToRef(point, this._tempVector3);
  53183. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  53184. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  53185. if (d < 0)
  53186. return false;
  53187. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  53188. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  53189. return d >= 0;
  53190. };
  53191. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  53192. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  53193. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  53194. if (distance > this._velocityWorldLength + max + sphereRadius) {
  53195. return false;
  53196. }
  53197. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  53198. return false;
  53199. return true;
  53200. };
  53201. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  53202. var t0;
  53203. var embeddedInPlane = false;
  53204. //defensive programming, actually not needed.
  53205. if (!trianglePlaneArray) {
  53206. trianglePlaneArray = [];
  53207. }
  53208. if (!trianglePlaneArray[faceIndex]) {
  53209. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  53210. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  53211. }
  53212. var trianglePlane = trianglePlaneArray[faceIndex];
  53213. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  53214. return;
  53215. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  53216. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  53217. if (normalDotVelocity == 0) {
  53218. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  53219. return;
  53220. embeddedInPlane = true;
  53221. t0 = 0;
  53222. }
  53223. else {
  53224. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  53225. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  53226. if (t0 > t1) {
  53227. var temp = t1;
  53228. t1 = t0;
  53229. t0 = temp;
  53230. }
  53231. if (t0 > 1.0 || t1 < 0.0)
  53232. return;
  53233. if (t0 < 0)
  53234. t0 = 0;
  53235. if (t0 > 1.0)
  53236. t0 = 1.0;
  53237. }
  53238. this._collisionPoint.copyFromFloats(0, 0, 0);
  53239. var found = false;
  53240. var t = 1.0;
  53241. if (!embeddedInPlane) {
  53242. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  53243. this._velocity.scaleToRef(t0, this._tempVector);
  53244. this._planeIntersectionPoint.addInPlace(this._tempVector);
  53245. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  53246. found = true;
  53247. t = t0;
  53248. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  53249. }
  53250. }
  53251. if (!found) {
  53252. var velocitySquaredLength = this._velocity.lengthSquared();
  53253. var a = velocitySquaredLength;
  53254. this._basePoint.subtractToRef(p1, this._tempVector);
  53255. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  53256. var c = this._tempVector.lengthSquared() - 1.0;
  53257. var lowestRoot = getLowestRoot(a, b, c, t);
  53258. if (lowestRoot.found) {
  53259. t = lowestRoot.root;
  53260. found = true;
  53261. this._collisionPoint.copyFrom(p1);
  53262. }
  53263. this._basePoint.subtractToRef(p2, this._tempVector);
  53264. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  53265. c = this._tempVector.lengthSquared() - 1.0;
  53266. lowestRoot = getLowestRoot(a, b, c, t);
  53267. if (lowestRoot.found) {
  53268. t = lowestRoot.root;
  53269. found = true;
  53270. this._collisionPoint.copyFrom(p2);
  53271. }
  53272. this._basePoint.subtractToRef(p3, this._tempVector);
  53273. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  53274. c = this._tempVector.lengthSquared() - 1.0;
  53275. lowestRoot = getLowestRoot(a, b, c, t);
  53276. if (lowestRoot.found) {
  53277. t = lowestRoot.root;
  53278. found = true;
  53279. this._collisionPoint.copyFrom(p3);
  53280. }
  53281. p2.subtractToRef(p1, this._edge);
  53282. p1.subtractToRef(this._basePoint, this._baseToVertex);
  53283. var edgeSquaredLength = this._edge.lengthSquared();
  53284. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  53285. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  53286. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  53287. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  53288. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  53289. lowestRoot = getLowestRoot(a, b, c, t);
  53290. if (lowestRoot.found) {
  53291. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  53292. if (f >= 0.0 && f <= 1.0) {
  53293. t = lowestRoot.root;
  53294. found = true;
  53295. this._edge.scaleInPlace(f);
  53296. p1.addToRef(this._edge, this._collisionPoint);
  53297. }
  53298. }
  53299. p3.subtractToRef(p2, this._edge);
  53300. p2.subtractToRef(this._basePoint, this._baseToVertex);
  53301. edgeSquaredLength = this._edge.lengthSquared();
  53302. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  53303. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  53304. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  53305. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  53306. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  53307. lowestRoot = getLowestRoot(a, b, c, t);
  53308. if (lowestRoot.found) {
  53309. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  53310. if (f >= 0.0 && f <= 1.0) {
  53311. t = lowestRoot.root;
  53312. found = true;
  53313. this._edge.scaleInPlace(f);
  53314. p2.addToRef(this._edge, this._collisionPoint);
  53315. }
  53316. }
  53317. p1.subtractToRef(p3, this._edge);
  53318. p3.subtractToRef(this._basePoint, this._baseToVertex);
  53319. edgeSquaredLength = this._edge.lengthSquared();
  53320. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  53321. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  53322. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  53323. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  53324. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  53325. lowestRoot = getLowestRoot(a, b, c, t);
  53326. if (lowestRoot.found) {
  53327. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  53328. if (f >= 0.0 && f <= 1.0) {
  53329. t = lowestRoot.root;
  53330. found = true;
  53331. this._edge.scaleInPlace(f);
  53332. p3.addToRef(this._edge, this._collisionPoint);
  53333. }
  53334. }
  53335. }
  53336. if (found) {
  53337. var distToCollision = t * this._velocity.length();
  53338. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  53339. if (!this.intersectionPoint) {
  53340. this.intersectionPoint = this._collisionPoint.clone();
  53341. }
  53342. else {
  53343. this.intersectionPoint.copyFrom(this._collisionPoint);
  53344. }
  53345. this._nearestDistance = distToCollision;
  53346. this.collisionFound = true;
  53347. }
  53348. }
  53349. };
  53350. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  53351. for (var i = indexStart; i < indexEnd; i += 3) {
  53352. var p1 = pts[indices[i] - decal];
  53353. var p2 = pts[indices[i + 1] - decal];
  53354. var p3 = pts[indices[i + 2] - decal];
  53355. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  53356. }
  53357. };
  53358. Collider.prototype._getResponse = function (pos, vel) {
  53359. pos.addToRef(vel, this._destinationPoint);
  53360. vel.scaleInPlace((this._nearestDistance / vel.length()));
  53361. this._basePoint.addToRef(vel, pos);
  53362. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  53363. this._slidePlaneNormal.normalize();
  53364. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  53365. pos.addInPlace(this._displacementVector);
  53366. this.intersectionPoint.addInPlace(this._displacementVector);
  53367. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  53368. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  53369. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  53370. };
  53371. return Collider;
  53372. }());
  53373. BABYLON.Collider = Collider;
  53374. })(BABYLON || (BABYLON = {}));
  53375. //# sourceMappingURL=babylon.collider.js.map
  53376. "use strict";
  53377. var BABYLON;
  53378. (function (BABYLON) {
  53379. //WebWorker code will be inserted to this variable.
  53380. BABYLON.CollisionWorker = "";
  53381. var WorkerTaskType;
  53382. (function (WorkerTaskType) {
  53383. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  53384. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  53385. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  53386. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  53387. var WorkerReplyType;
  53388. (function (WorkerReplyType) {
  53389. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  53390. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  53391. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  53392. var CollisionCoordinatorWorker = /** @class */ (function () {
  53393. function CollisionCoordinatorWorker() {
  53394. var _this = this;
  53395. this._scaledPosition = BABYLON.Vector3.Zero();
  53396. this._scaledVelocity = BABYLON.Vector3.Zero();
  53397. this.onMeshUpdated = function (transformNode) {
  53398. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  53399. };
  53400. this.onGeometryUpdated = function (geometry) {
  53401. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  53402. };
  53403. this._afterRender = function () {
  53404. if (!_this._init)
  53405. return;
  53406. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  53407. return;
  53408. }
  53409. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  53410. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  53411. if (_this._runningUpdated > 4) {
  53412. return;
  53413. }
  53414. ++_this._runningUpdated;
  53415. var payload = {
  53416. updatedMeshes: _this._addUpdateMeshesList,
  53417. updatedGeometries: _this._addUpdateGeometriesList,
  53418. removedGeometries: _this._toRemoveGeometryArray,
  53419. removedMeshes: _this._toRemoveMeshesArray
  53420. };
  53421. var message = {
  53422. payload: payload,
  53423. taskType: WorkerTaskType.UPDATE
  53424. };
  53425. var serializable = [];
  53426. for (var id in payload.updatedGeometries) {
  53427. if (payload.updatedGeometries.hasOwnProperty(id)) {
  53428. //prepare transferables
  53429. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  53430. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  53431. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  53432. }
  53433. }
  53434. _this._worker.postMessage(message, serializable);
  53435. _this._addUpdateMeshesList = {};
  53436. _this._addUpdateGeometriesList = {};
  53437. _this._toRemoveGeometryArray = [];
  53438. _this._toRemoveMeshesArray = [];
  53439. };
  53440. this._onMessageFromWorker = function (e) {
  53441. var returnData = e.data;
  53442. if (returnData.error != WorkerReplyType.SUCCESS) {
  53443. //TODO what errors can be returned from the worker?
  53444. BABYLON.Tools.Warn("error returned from worker!");
  53445. return;
  53446. }
  53447. switch (returnData.taskType) {
  53448. case WorkerTaskType.INIT:
  53449. _this._init = true;
  53450. //Update the worked with ALL of the scene's current state
  53451. _this._scene.meshes.forEach(function (mesh) {
  53452. _this.onMeshAdded(mesh);
  53453. });
  53454. _this._scene.getGeometries().forEach(function (geometry) {
  53455. _this.onGeometryAdded(geometry);
  53456. });
  53457. break;
  53458. case WorkerTaskType.UPDATE:
  53459. _this._runningUpdated--;
  53460. break;
  53461. case WorkerTaskType.COLLIDE:
  53462. var returnPayload = returnData.payload;
  53463. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  53464. return;
  53465. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  53466. if (callback) {
  53467. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  53468. if (mesh) {
  53469. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  53470. }
  53471. }
  53472. //cleanup
  53473. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  53474. break;
  53475. }
  53476. };
  53477. this._collisionsCallbackArray = [];
  53478. this._init = false;
  53479. this._runningUpdated = 0;
  53480. this._addUpdateMeshesList = {};
  53481. this._addUpdateGeometriesList = {};
  53482. this._toRemoveGeometryArray = [];
  53483. this._toRemoveMeshesArray = [];
  53484. }
  53485. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  53486. if (!this._init)
  53487. return;
  53488. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  53489. return;
  53490. position.divideToRef(collider._radius, this._scaledPosition);
  53491. displacement.divideToRef(collider._radius, this._scaledVelocity);
  53492. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  53493. var payload = {
  53494. collider: {
  53495. position: this._scaledPosition.asArray(),
  53496. velocity: this._scaledVelocity.asArray(),
  53497. radius: collider._radius.asArray()
  53498. },
  53499. collisionId: collisionIndex,
  53500. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  53501. maximumRetry: maximumRetry
  53502. };
  53503. var message = {
  53504. payload: payload,
  53505. taskType: WorkerTaskType.COLLIDE
  53506. };
  53507. this._worker.postMessage(message);
  53508. };
  53509. CollisionCoordinatorWorker.prototype.init = function (scene) {
  53510. this._scene = scene;
  53511. this._scene.registerAfterRender(this._afterRender);
  53512. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  53513. this._worker = new Worker(workerUrl);
  53514. this._worker.onmessage = this._onMessageFromWorker;
  53515. var message = {
  53516. payload: {},
  53517. taskType: WorkerTaskType.INIT
  53518. };
  53519. this._worker.postMessage(message);
  53520. };
  53521. CollisionCoordinatorWorker.prototype.destroy = function () {
  53522. this._scene.unregisterAfterRender(this._afterRender);
  53523. this._worker.terminate();
  53524. };
  53525. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  53526. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  53527. this.onMeshUpdated(mesh);
  53528. };
  53529. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  53530. this._toRemoveMeshesArray.push(mesh.uniqueId);
  53531. };
  53532. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  53533. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  53534. geometry.onGeometryUpdated = this.onGeometryUpdated;
  53535. this.onGeometryUpdated(geometry);
  53536. };
  53537. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  53538. this._toRemoveGeometryArray.push(geometry.id);
  53539. };
  53540. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  53541. var submeshes = [];
  53542. if (mesh.subMeshes) {
  53543. submeshes = mesh.subMeshes.map(function (sm, idx) {
  53544. var boundingInfo = sm.getBoundingInfo();
  53545. return {
  53546. position: idx,
  53547. verticesStart: sm.verticesStart,
  53548. verticesCount: sm.verticesCount,
  53549. indexStart: sm.indexStart,
  53550. indexCount: sm.indexCount,
  53551. hasMaterial: !!sm.getMaterial(),
  53552. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  53553. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  53554. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  53555. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  53556. };
  53557. });
  53558. }
  53559. var geometryId = null;
  53560. if (mesh instanceof BABYLON.Mesh) {
  53561. var geometry = mesh.geometry;
  53562. geometryId = geometry ? geometry.id : null;
  53563. }
  53564. else if (mesh instanceof BABYLON.InstancedMesh) {
  53565. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  53566. geometryId = geometry ? geometry.id : null;
  53567. }
  53568. var boundingInfo = mesh.getBoundingInfo();
  53569. return {
  53570. uniqueId: mesh.uniqueId,
  53571. id: mesh.id,
  53572. name: mesh.name,
  53573. geometryId: geometryId,
  53574. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  53575. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  53576. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  53577. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  53578. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  53579. subMeshes: submeshes,
  53580. checkCollisions: mesh.checkCollisions
  53581. };
  53582. };
  53583. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  53584. return {
  53585. id: geometry.id,
  53586. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  53587. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  53588. indices: new Uint32Array(geometry.getIndices() || []),
  53589. };
  53590. };
  53591. return CollisionCoordinatorWorker;
  53592. }());
  53593. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  53594. var CollisionCoordinatorLegacy = /** @class */ (function () {
  53595. function CollisionCoordinatorLegacy() {
  53596. this._scaledPosition = BABYLON.Vector3.Zero();
  53597. this._scaledVelocity = BABYLON.Vector3.Zero();
  53598. this._finalPosition = BABYLON.Vector3.Zero();
  53599. }
  53600. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  53601. position.divideToRef(collider._radius, this._scaledPosition);
  53602. displacement.divideToRef(collider._radius, this._scaledVelocity);
  53603. collider.collidedMesh = null;
  53604. collider._retry = 0;
  53605. collider._initialVelocity = this._scaledVelocity;
  53606. collider._initialPosition = this._scaledPosition;
  53607. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  53608. this._finalPosition.multiplyInPlace(collider._radius);
  53609. //run the callback
  53610. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  53611. };
  53612. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  53613. this._scene = scene;
  53614. };
  53615. CollisionCoordinatorLegacy.prototype.destroy = function () {
  53616. //Legacy need no destruction method.
  53617. };
  53618. //No update in legacy mode
  53619. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  53620. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  53621. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  53622. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  53623. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  53624. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  53625. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  53626. if (excludedMesh === void 0) { excludedMesh = null; }
  53627. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  53628. if (collider._retry >= maximumRetry) {
  53629. finalPosition.copyFrom(position);
  53630. return;
  53631. }
  53632. // Check if this is a mesh else camera or -1
  53633. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  53634. collider._initialize(position, velocity, closeDistance);
  53635. // Check all meshes
  53636. for (var index = 0; index < this._scene.meshes.length; index++) {
  53637. var mesh = this._scene.meshes[index];
  53638. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  53639. mesh._checkCollision(collider);
  53640. }
  53641. }
  53642. if (!collider.collisionFound) {
  53643. position.addToRef(velocity, finalPosition);
  53644. return;
  53645. }
  53646. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  53647. collider._getResponse(position, velocity);
  53648. }
  53649. if (velocity.length() <= closeDistance) {
  53650. finalPosition.copyFrom(position);
  53651. return;
  53652. }
  53653. collider._retry++;
  53654. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  53655. };
  53656. return CollisionCoordinatorLegacy;
  53657. }());
  53658. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  53659. })(BABYLON || (BABYLON = {}));
  53660. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  53661. "use strict";
  53662. var BABYLON;
  53663. (function (BABYLON) {
  53664. /**
  53665. * A particle represents one of the element emitted by a particle system.
  53666. * This is mainly define by its coordinates, direction, velocity and age.
  53667. */
  53668. var Particle = /** @class */ (function () {
  53669. /**
  53670. * Creates a new instance Particle
  53671. * @param particleSystem the particle system the particle belongs to
  53672. */
  53673. function Particle(
  53674. /**
  53675. * particleSystem the particle system the particle belongs to.
  53676. */
  53677. particleSystem) {
  53678. this.particleSystem = particleSystem;
  53679. /**
  53680. * The world position of the particle in the scene.
  53681. */
  53682. this.position = BABYLON.Vector3.Zero();
  53683. /**
  53684. * The world direction of the particle in the scene.
  53685. */
  53686. this.direction = BABYLON.Vector3.Zero();
  53687. /**
  53688. * The color of the particle.
  53689. */
  53690. this.color = new BABYLON.Color4(0, 0, 0, 0);
  53691. /**
  53692. * The color change of the particle per step.
  53693. */
  53694. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  53695. /**
  53696. * Defines how long will the life of the particle be.
  53697. */
  53698. this.lifeTime = 1.0;
  53699. /**
  53700. * The current age of the particle.
  53701. */
  53702. this.age = 0;
  53703. /**
  53704. * The current size of the particle.
  53705. */
  53706. this.size = 0;
  53707. /**
  53708. * The current angle of the particle.
  53709. */
  53710. this.angle = 0;
  53711. /**
  53712. * Defines how fast is the angle changing.
  53713. */
  53714. this.angularSpeed = 0;
  53715. /**
  53716. * Defines the cell index used by the particle to be rendered from a sprite.
  53717. */
  53718. this.cellIndex = 0;
  53719. this._currentFrameCounter = 0;
  53720. if (!this.particleSystem.isAnimationSheetEnabled) {
  53721. return;
  53722. }
  53723. this.updateCellInfoFromSystem();
  53724. }
  53725. Particle.prototype.updateCellInfoFromSystem = function () {
  53726. this.cellIndex = this.particleSystem.startSpriteCellID;
  53727. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  53728. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  53729. }
  53730. else {
  53731. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  53732. }
  53733. };
  53734. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  53735. // (ageOffset / scaledUpdateSpeed) / available cells
  53736. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  53737. this._currentFrameCounter += scaledUpdateSpeed;
  53738. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  53739. this._currentFrameCounter = 0;
  53740. this.cellIndex++;
  53741. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  53742. this.cellIndex = this.particleSystem.endSpriteCellID;
  53743. }
  53744. }
  53745. };
  53746. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  53747. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  53748. this.cellIndex++;
  53749. this._currentFrameCounter = 0;
  53750. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  53751. if (this.particleSystem.spriteCellLoop) {
  53752. this.cellIndex = this.particleSystem.startSpriteCellID;
  53753. }
  53754. else {
  53755. this.cellIndex = this.particleSystem.endSpriteCellID;
  53756. }
  53757. }
  53758. }
  53759. else {
  53760. this._currentFrameCounter++;
  53761. }
  53762. };
  53763. /**
  53764. * Copy the properties of particle to another one.
  53765. * @param other the particle to copy the information to.
  53766. */
  53767. Particle.prototype.copyTo = function (other) {
  53768. other.position.copyFrom(this.position);
  53769. other.direction.copyFrom(this.direction);
  53770. other.color.copyFrom(this.color);
  53771. other.colorStep.copyFrom(this.colorStep);
  53772. other.lifeTime = this.lifeTime;
  53773. other.age = this.age;
  53774. other.size = this.size;
  53775. other.angle = this.angle;
  53776. other.angularSpeed = this.angularSpeed;
  53777. other.particleSystem = this.particleSystem;
  53778. other.cellIndex = this.cellIndex;
  53779. };
  53780. return Particle;
  53781. }());
  53782. BABYLON.Particle = Particle;
  53783. })(BABYLON || (BABYLON = {}));
  53784. //# sourceMappingURL=babylon.particle.js.map
  53785. "use strict";
  53786. var BABYLON;
  53787. (function (BABYLON) {
  53788. /**
  53789. * This represents a particle system in Babylon.
  53790. * 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.
  53791. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  53792. * @example https://doc.babylonjs.com/babylon101/particles
  53793. */
  53794. var ParticleSystem = /** @class */ (function () {
  53795. /**
  53796. * Instantiates a particle system.
  53797. * 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.
  53798. * @param name The name of the particle system
  53799. * @param capacity The max number of particles alive at the same time
  53800. * @param scene The scene the particle system belongs to
  53801. * @param customEffect a custom effect used to change the way particles are rendered by default
  53802. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  53803. * @param epsilon Offset used to render the particles
  53804. */
  53805. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  53806. if (customEffect === void 0) { customEffect = null; }
  53807. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  53808. if (epsilon === void 0) { epsilon = 0.01; }
  53809. var _this = this;
  53810. /**
  53811. * List of animations used by the particle system.
  53812. */
  53813. this.animations = [];
  53814. /**
  53815. * The rendering group used by the Particle system to chose when to render.
  53816. */
  53817. this.renderingGroupId = 0;
  53818. /**
  53819. * The emitter represents the Mesh or position we are attaching the particle system to.
  53820. */
  53821. this.emitter = null;
  53822. /**
  53823. * The maximum number of particles to emit per frame
  53824. */
  53825. this.emitRate = 10;
  53826. /**
  53827. * If you want to launch only a few particles at once, that can be done, as well.
  53828. */
  53829. this.manualEmitCount = -1;
  53830. /**
  53831. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  53832. */
  53833. this.updateSpeed = 0.01;
  53834. /**
  53835. * The amount of time the particle system is running (depends of the overall update speed).
  53836. */
  53837. this.targetStopDuration = 0;
  53838. /**
  53839. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  53840. */
  53841. this.disposeOnStop = false;
  53842. /**
  53843. * Minimum power of emitting particles.
  53844. */
  53845. this.minEmitPower = 1;
  53846. /**
  53847. * Maximum power of emitting particles.
  53848. */
  53849. this.maxEmitPower = 1;
  53850. /**
  53851. * Minimum life time of emitting particles.
  53852. */
  53853. this.minLifeTime = 1;
  53854. /**
  53855. * Maximum life time of emitting particles.
  53856. */
  53857. this.maxLifeTime = 1;
  53858. /**
  53859. * Minimum Size of emitting particles.
  53860. */
  53861. this.minSize = 1;
  53862. /**
  53863. * Maximum Size of emitting particles.
  53864. */
  53865. this.maxSize = 1;
  53866. /**
  53867. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  53868. */
  53869. this.minAngularSpeed = 0;
  53870. /**
  53871. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  53872. */
  53873. this.maxAngularSpeed = 0;
  53874. /**
  53875. * The layer mask we are rendering the particles through.
  53876. */
  53877. this.layerMask = 0x0FFFFFFF;
  53878. /**
  53879. * This can help using your own shader to render the particle system.
  53880. * The according effect will be created
  53881. */
  53882. this.customShader = null;
  53883. /**
  53884. * By default particle system starts as soon as they are created. This prevents the
  53885. * automatic start to happen and let you decide when to start emitting particles.
  53886. */
  53887. this.preventAutoStart = false;
  53888. /**
  53889. * Callback triggered when the particle animation is ending.
  53890. */
  53891. this.onAnimationEnd = null;
  53892. /**
  53893. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  53894. */
  53895. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  53896. /**
  53897. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  53898. * to override the particles.
  53899. */
  53900. this.forceDepthWrite = false;
  53901. /**
  53902. * You can use gravity if you want to give an orientation to your particles.
  53903. */
  53904. this.gravity = BABYLON.Vector3.Zero();
  53905. /**
  53906. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  53907. */
  53908. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53909. /**
  53910. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  53911. */
  53912. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53913. /**
  53914. * Color the particle will have at the end of its lifetime.
  53915. */
  53916. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  53917. /**
  53918. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  53919. */
  53920. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53921. /**
  53922. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  53923. */
  53924. this.spriteCellLoop = true;
  53925. /**
  53926. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  53927. */
  53928. this.spriteCellChangeSpeed = 0;
  53929. /**
  53930. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  53931. */
  53932. this.startSpriteCellID = 0;
  53933. /**
  53934. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  53935. */
  53936. this.endSpriteCellID = 0;
  53937. /**
  53938. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  53939. */
  53940. this.spriteCellWidth = 0;
  53941. /**
  53942. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  53943. */
  53944. this.spriteCellHeight = 0;
  53945. /**
  53946. * An event triggered when the system is disposed.
  53947. */
  53948. this.onDisposeObservable = new BABYLON.Observable();
  53949. this._particles = new Array();
  53950. this._stockParticles = new Array();
  53951. this._newPartsExcess = 0;
  53952. this._vertexBuffers = {};
  53953. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  53954. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  53955. this._scaledDirection = BABYLON.Vector3.Zero();
  53956. this._scaledGravity = BABYLON.Vector3.Zero();
  53957. this._currentRenderId = -1;
  53958. this._started = false;
  53959. this._stopped = false;
  53960. this._actualFrame = 0;
  53961. this._vertexBufferSize = 11;
  53962. // start of sub system methods
  53963. /**
  53964. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  53965. * Its lifetime will start back at 0.
  53966. */
  53967. this.recycleParticle = function (particle) {
  53968. var lastParticle = _this._particles.pop();
  53969. if (lastParticle !== particle) {
  53970. lastParticle.copyTo(particle);
  53971. }
  53972. _this._stockParticles.push(lastParticle);
  53973. };
  53974. this._createParticle = function () {
  53975. var particle;
  53976. if (_this._stockParticles.length !== 0) {
  53977. particle = _this._stockParticles.pop();
  53978. particle.age = 0;
  53979. particle.cellIndex = _this.startSpriteCellID;
  53980. }
  53981. else {
  53982. particle = new BABYLON.Particle(_this);
  53983. }
  53984. return particle;
  53985. };
  53986. this._emitFromParticle = function (particle) {
  53987. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  53988. return;
  53989. }
  53990. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  53991. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  53992. subSystem._rootParticleSystem = _this;
  53993. _this.activeSubSystems.push(subSystem);
  53994. subSystem.start();
  53995. };
  53996. this._appendParticleVertexes = null;
  53997. this.id = name;
  53998. this.name = name;
  53999. this._capacity = capacity;
  54000. this._epsilon = epsilon;
  54001. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  54002. if (isAnimationSheetEnabled) {
  54003. this._vertexBufferSize = 12;
  54004. }
  54005. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  54006. this._customEffect = customEffect;
  54007. scene.particleSystems.push(this);
  54008. this._createIndexBuffer();
  54009. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  54010. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  54011. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  54012. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  54013. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  54014. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  54015. if (this._isAnimationSheetEnabled) {
  54016. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  54017. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  54018. }
  54019. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54020. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54021. this._vertexBuffers["options"] = options;
  54022. // Default emitter type
  54023. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  54024. this.updateFunction = function (particles) {
  54025. for (var index = 0; index < particles.length; index++) {
  54026. var particle = particles[index];
  54027. particle.age += _this._scaledUpdateSpeed;
  54028. if (particle.age >= particle.lifeTime) {
  54029. _this._emitFromParticle(particle);
  54030. _this.recycleParticle(particle);
  54031. index--;
  54032. continue;
  54033. }
  54034. else {
  54035. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  54036. particle.color.addInPlace(_this._scaledColorStep);
  54037. if (particle.color.a < 0)
  54038. particle.color.a = 0;
  54039. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  54040. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  54041. particle.position.addInPlace(_this._scaledDirection);
  54042. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  54043. particle.direction.addInPlace(_this._scaledGravity);
  54044. if (_this._isAnimationSheetEnabled) {
  54045. particle.updateCellIndex(_this._scaledUpdateSpeed);
  54046. }
  54047. }
  54048. }
  54049. };
  54050. }
  54051. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  54052. /**
  54053. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  54054. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54055. */
  54056. get: function () {
  54057. if (this.particleEmitterType.direction1) {
  54058. return this.particleEmitterType.direction1;
  54059. }
  54060. return BABYLON.Vector3.Zero();
  54061. },
  54062. set: function (value) {
  54063. if (this.particleEmitterType.direction1) {
  54064. this.particleEmitterType.direction1 = value;
  54065. }
  54066. },
  54067. enumerable: true,
  54068. configurable: true
  54069. });
  54070. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  54071. /**
  54072. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  54073. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54074. */
  54075. get: function () {
  54076. if (this.particleEmitterType.direction2) {
  54077. return this.particleEmitterType.direction2;
  54078. }
  54079. return BABYLON.Vector3.Zero();
  54080. },
  54081. set: function (value) {
  54082. if (this.particleEmitterType.direction2) {
  54083. this.particleEmitterType.direction2 = value;
  54084. }
  54085. },
  54086. enumerable: true,
  54087. configurable: true
  54088. });
  54089. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  54090. /**
  54091. * 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.
  54092. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54093. */
  54094. get: function () {
  54095. if (this.particleEmitterType.minEmitBox) {
  54096. return this.particleEmitterType.minEmitBox;
  54097. }
  54098. return BABYLON.Vector3.Zero();
  54099. },
  54100. set: function (value) {
  54101. if (this.particleEmitterType.minEmitBox) {
  54102. this.particleEmitterType.minEmitBox = value;
  54103. }
  54104. },
  54105. enumerable: true,
  54106. configurable: true
  54107. });
  54108. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  54109. /**
  54110. * 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.
  54111. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54112. */
  54113. get: function () {
  54114. if (this.particleEmitterType.maxEmitBox) {
  54115. return this.particleEmitterType.maxEmitBox;
  54116. }
  54117. return BABYLON.Vector3.Zero();
  54118. },
  54119. set: function (value) {
  54120. if (this.particleEmitterType.maxEmitBox) {
  54121. this.particleEmitterType.maxEmitBox = value;
  54122. }
  54123. },
  54124. enumerable: true,
  54125. configurable: true
  54126. });
  54127. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  54128. /**
  54129. * Sets a callback that will be triggered when the system is disposed.
  54130. */
  54131. set: function (callback) {
  54132. if (this._onDisposeObserver) {
  54133. this.onDisposeObservable.remove(this._onDisposeObserver);
  54134. }
  54135. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54136. },
  54137. enumerable: true,
  54138. configurable: true
  54139. });
  54140. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  54141. /**
  54142. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  54143. */
  54144. get: function () {
  54145. return this._isAnimationSheetEnabled;
  54146. },
  54147. enumerable: true,
  54148. configurable: true
  54149. });
  54150. Object.defineProperty(ParticleSystem.prototype, "particles", {
  54151. //end of Sub-emitter
  54152. /**
  54153. * Gets the current list of active particles
  54154. */
  54155. get: function () {
  54156. return this._particles;
  54157. },
  54158. enumerable: true,
  54159. configurable: true
  54160. });
  54161. /**
  54162. * Returns the string "ParticleSystem"
  54163. * @returns a string containing the class name
  54164. */
  54165. ParticleSystem.prototype.getClassName = function () {
  54166. return "ParticleSystem";
  54167. };
  54168. ParticleSystem.prototype._createIndexBuffer = function () {
  54169. var indices = [];
  54170. var index = 0;
  54171. for (var count = 0; count < this._capacity; count++) {
  54172. indices.push(index);
  54173. indices.push(index + 1);
  54174. indices.push(index + 2);
  54175. indices.push(index);
  54176. indices.push(index + 2);
  54177. indices.push(index + 3);
  54178. index += 4;
  54179. }
  54180. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  54181. };
  54182. /**
  54183. * Gets the maximum number of particles active at the same time.
  54184. * @returns The max number of active particles.
  54185. */
  54186. ParticleSystem.prototype.getCapacity = function () {
  54187. return this._capacity;
  54188. };
  54189. /**
  54190. * Gets Wether there are still active particles in the system.
  54191. * @returns True if it is alive, otherwise false.
  54192. */
  54193. ParticleSystem.prototype.isAlive = function () {
  54194. return this._alive;
  54195. };
  54196. /**
  54197. * Gets Wether the system has been started.
  54198. * @returns True if it has been started, otherwise false.
  54199. */
  54200. ParticleSystem.prototype.isStarted = function () {
  54201. return this._started;
  54202. };
  54203. /**
  54204. * Starts the particle system and begins to emit.
  54205. */
  54206. ParticleSystem.prototype.start = function () {
  54207. this._started = true;
  54208. this._stopped = false;
  54209. this._actualFrame = 0;
  54210. if (this.subEmitters && this.subEmitters.length != 0) {
  54211. this.activeSubSystems = new Array();
  54212. }
  54213. };
  54214. /**
  54215. * Stops the particle system.
  54216. * @param stopSubEmitters if true it will stop the current system and all created sub-Systems if false it will stop the current root system only, this param is used by the root particle system only. the default value is true.
  54217. */
  54218. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  54219. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  54220. this._stopped = true;
  54221. if (stopSubEmitters) {
  54222. this._stopSubEmitters();
  54223. }
  54224. };
  54225. // animation sheet
  54226. /**
  54227. * Remove all active particles
  54228. */
  54229. ParticleSystem.prototype.reset = function () {
  54230. this._stockParticles = [];
  54231. this._particles = [];
  54232. };
  54233. /**
  54234. * @ignore (for internal use only)
  54235. */
  54236. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  54237. var offset = index * this._vertexBufferSize;
  54238. this._vertexData[offset] = particle.position.x;
  54239. this._vertexData[offset + 1] = particle.position.y;
  54240. this._vertexData[offset + 2] = particle.position.z;
  54241. this._vertexData[offset + 3] = particle.color.r;
  54242. this._vertexData[offset + 4] = particle.color.g;
  54243. this._vertexData[offset + 5] = particle.color.b;
  54244. this._vertexData[offset + 6] = particle.color.a;
  54245. this._vertexData[offset + 7] = particle.angle;
  54246. this._vertexData[offset + 8] = particle.size;
  54247. this._vertexData[offset + 9] = offsetX;
  54248. this._vertexData[offset + 10] = offsetY;
  54249. };
  54250. /**
  54251. * @ignore (for internal use only)
  54252. */
  54253. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  54254. if (offsetX === 0)
  54255. offsetX = this._epsilon;
  54256. else if (offsetX === 1)
  54257. offsetX = 1 - this._epsilon;
  54258. if (offsetY === 0)
  54259. offsetY = this._epsilon;
  54260. else if (offsetY === 1)
  54261. offsetY = 1 - this._epsilon;
  54262. var offset = index * this._vertexBufferSize;
  54263. this._vertexData[offset] = particle.position.x;
  54264. this._vertexData[offset + 1] = particle.position.y;
  54265. this._vertexData[offset + 2] = particle.position.z;
  54266. this._vertexData[offset + 3] = particle.color.r;
  54267. this._vertexData[offset + 4] = particle.color.g;
  54268. this._vertexData[offset + 5] = particle.color.b;
  54269. this._vertexData[offset + 6] = particle.color.a;
  54270. this._vertexData[offset + 7] = particle.angle;
  54271. this._vertexData[offset + 8] = particle.size;
  54272. this._vertexData[offset + 9] = offsetX;
  54273. this._vertexData[offset + 10] = offsetY;
  54274. this._vertexData[offset + 11] = particle.cellIndex;
  54275. };
  54276. ParticleSystem.prototype._stopSubEmitters = function () {
  54277. if (!this.activeSubSystems) {
  54278. return;
  54279. }
  54280. this.activeSubSystems.forEach(function (subSystem) {
  54281. subSystem.stop(true);
  54282. });
  54283. this.activeSubSystems = new Array();
  54284. };
  54285. ParticleSystem.prototype._removeFromRoot = function () {
  54286. if (!this._rootParticleSystem) {
  54287. return;
  54288. }
  54289. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  54290. if (index !== -1) {
  54291. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  54292. }
  54293. };
  54294. // end of sub system methods
  54295. ParticleSystem.prototype._update = function (newParticles) {
  54296. // Update current
  54297. this._alive = this._particles.length > 0;
  54298. this.updateFunction(this._particles);
  54299. // Add new ones
  54300. var worldMatrix;
  54301. if (this.emitter.position) {
  54302. var emitterMesh = this.emitter;
  54303. worldMatrix = emitterMesh.getWorldMatrix();
  54304. }
  54305. else {
  54306. var emitterPosition = this.emitter;
  54307. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  54308. }
  54309. var particle;
  54310. for (var index = 0; index < newParticles; index++) {
  54311. if (this._particles.length === this._capacity) {
  54312. break;
  54313. }
  54314. particle = this._createParticle();
  54315. this._particles.push(particle);
  54316. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  54317. if (this.startPositionFunction) {
  54318. this.startPositionFunction(worldMatrix, particle.position, particle);
  54319. }
  54320. else {
  54321. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  54322. }
  54323. if (this.startDirectionFunction) {
  54324. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  54325. }
  54326. else {
  54327. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  54328. }
  54329. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  54330. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  54331. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  54332. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  54333. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  54334. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  54335. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  54336. }
  54337. };
  54338. ParticleSystem.prototype._getEffect = function () {
  54339. if (this._customEffect) {
  54340. return this._customEffect;
  54341. }
  54342. ;
  54343. var defines = [];
  54344. if (this._scene.clipPlane) {
  54345. defines.push("#define CLIPPLANE");
  54346. }
  54347. if (this._isAnimationSheetEnabled) {
  54348. defines.push("#define ANIMATESHEET");
  54349. }
  54350. // Effect
  54351. var join = defines.join("\n");
  54352. if (this._cachedDefines !== join) {
  54353. this._cachedDefines = join;
  54354. var attributesNamesOrOptions;
  54355. var effectCreationOption;
  54356. if (this._isAnimationSheetEnabled) {
  54357. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  54358. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  54359. }
  54360. else {
  54361. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  54362. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  54363. }
  54364. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  54365. }
  54366. return this._effect;
  54367. };
  54368. /**
  54369. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  54370. */
  54371. ParticleSystem.prototype.animate = function () {
  54372. if (!this._started)
  54373. return;
  54374. var effect = this._getEffect();
  54375. // Check
  54376. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  54377. return;
  54378. if (this._currentRenderId === this._scene.getRenderId()) {
  54379. return;
  54380. }
  54381. this._currentRenderId = this._scene.getRenderId();
  54382. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  54383. // determine the number of particles we need to create
  54384. var newParticles;
  54385. if (this.manualEmitCount > -1) {
  54386. newParticles = this.manualEmitCount;
  54387. this._newPartsExcess = 0;
  54388. this.manualEmitCount = 0;
  54389. }
  54390. else {
  54391. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  54392. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  54393. }
  54394. if (this._newPartsExcess > 1.0) {
  54395. newParticles += this._newPartsExcess >> 0;
  54396. this._newPartsExcess -= this._newPartsExcess >> 0;
  54397. }
  54398. this._alive = false;
  54399. if (!this._stopped) {
  54400. this._actualFrame += this._scaledUpdateSpeed;
  54401. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  54402. this.stop();
  54403. }
  54404. else {
  54405. newParticles = 0;
  54406. }
  54407. this._update(newParticles);
  54408. // Stopped?
  54409. if (this._stopped) {
  54410. if (!this._alive) {
  54411. this._started = false;
  54412. if (this.onAnimationEnd) {
  54413. this.onAnimationEnd();
  54414. }
  54415. if (this.disposeOnStop) {
  54416. this._scene._toBeDisposed.push(this);
  54417. }
  54418. }
  54419. }
  54420. // Animation sheet
  54421. if (this._isAnimationSheetEnabled) {
  54422. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  54423. }
  54424. else {
  54425. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  54426. }
  54427. // Update VBO
  54428. var offset = 0;
  54429. for (var index = 0; index < this._particles.length; index++) {
  54430. var particle = this._particles[index];
  54431. this._appendParticleVertexes(offset, particle);
  54432. offset += 4;
  54433. }
  54434. if (this._vertexBuffer) {
  54435. this._vertexBuffer.update(this._vertexData);
  54436. }
  54437. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  54438. this.stop();
  54439. }
  54440. };
  54441. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  54442. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  54443. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  54444. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  54445. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  54446. };
  54447. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  54448. this._appendParticleVertex(offset++, particle, 0, 0);
  54449. this._appendParticleVertex(offset++, particle, 1, 0);
  54450. this._appendParticleVertex(offset++, particle, 1, 1);
  54451. this._appendParticleVertex(offset++, particle, 0, 1);
  54452. };
  54453. /**
  54454. * Rebuilds the particle system.
  54455. */
  54456. ParticleSystem.prototype.rebuild = function () {
  54457. this._createIndexBuffer();
  54458. if (this._vertexBuffer) {
  54459. this._vertexBuffer._rebuild();
  54460. }
  54461. };
  54462. /**
  54463. * Is this system ready to be used/rendered
  54464. * @return true if the system is ready
  54465. */
  54466. ParticleSystem.prototype.isReady = function () {
  54467. var effect = this._getEffect();
  54468. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  54469. return false;
  54470. }
  54471. return true;
  54472. };
  54473. /**
  54474. * Renders the particle system in its current state.
  54475. * @returns the current number of particles
  54476. */
  54477. ParticleSystem.prototype.render = function () {
  54478. var effect = this._getEffect();
  54479. // Check
  54480. if (!this.isReady() || !this._particles.length) {
  54481. return 0;
  54482. }
  54483. var engine = this._scene.getEngine();
  54484. // Render
  54485. engine.enableEffect(effect);
  54486. engine.setState(false);
  54487. var viewMatrix = this._scene.getViewMatrix();
  54488. effect.setTexture("diffuseSampler", this.particleTexture);
  54489. effect.setMatrix("view", viewMatrix);
  54490. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  54491. if (this._isAnimationSheetEnabled && this.particleTexture) {
  54492. var baseSize = this.particleTexture.getBaseSize();
  54493. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  54494. }
  54495. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  54496. if (this._scene.clipPlane) {
  54497. var clipPlane = this._scene.clipPlane;
  54498. var invView = viewMatrix.clone();
  54499. invView.invert();
  54500. effect.setMatrix("invView", invView);
  54501. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  54502. }
  54503. // VBOs
  54504. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  54505. // Draw order
  54506. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  54507. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  54508. }
  54509. else {
  54510. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54511. }
  54512. if (this.forceDepthWrite) {
  54513. engine.setDepthWrite(true);
  54514. }
  54515. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  54516. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54517. return this._particles.length;
  54518. };
  54519. /**
  54520. * Disposes the particle system and free the associated resources
  54521. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  54522. */
  54523. ParticleSystem.prototype.dispose = function (disposeTexture) {
  54524. if (disposeTexture === void 0) { disposeTexture = true; }
  54525. if (this._vertexBuffer) {
  54526. this._vertexBuffer.dispose();
  54527. this._vertexBuffer = null;
  54528. }
  54529. if (this._indexBuffer) {
  54530. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54531. this._indexBuffer = null;
  54532. }
  54533. if (disposeTexture && this.particleTexture) {
  54534. this.particleTexture.dispose();
  54535. this.particleTexture = null;
  54536. }
  54537. this._removeFromRoot();
  54538. // Remove from scene
  54539. var index = this._scene.particleSystems.indexOf(this);
  54540. if (index > -1) {
  54541. this._scene.particleSystems.splice(index, 1);
  54542. }
  54543. // Callback
  54544. this.onDisposeObservable.notifyObservers(this);
  54545. this.onDisposeObservable.clear();
  54546. };
  54547. /**
  54548. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  54549. * @param radius The radius of the sphere to emit from
  54550. * @returns the emitter
  54551. */
  54552. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  54553. if (radius === void 0) { radius = 1; }
  54554. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  54555. this.particleEmitterType = particleEmitter;
  54556. return particleEmitter;
  54557. };
  54558. /**
  54559. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  54560. * @param radius The radius of the sphere to emit from
  54561. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  54562. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  54563. * @returns the emitter
  54564. */
  54565. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  54566. if (radius === void 0) { radius = 1; }
  54567. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  54568. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  54569. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  54570. this.particleEmitterType = particleEmitter;
  54571. return particleEmitter;
  54572. };
  54573. /**
  54574. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  54575. * @param radius The radius of the cone to emit from
  54576. * @param angle The base angle of the cone
  54577. * @returns the emitter
  54578. */
  54579. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  54580. if (radius === void 0) { radius = 1; }
  54581. if (angle === void 0) { angle = Math.PI / 4; }
  54582. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  54583. this.particleEmitterType = particleEmitter;
  54584. return particleEmitter;
  54585. };
  54586. // 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.
  54587. /**
  54588. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  54589. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  54590. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  54591. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  54592. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  54593. * @returns the emitter
  54594. */
  54595. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  54596. var particleEmitter = new BABYLON.BoxParticleEmitter();
  54597. this.particleEmitterType = particleEmitter;
  54598. this.direction1 = direction1;
  54599. this.direction2 = direction2;
  54600. this.minEmitBox = minEmitBox;
  54601. this.maxEmitBox = maxEmitBox;
  54602. return particleEmitter;
  54603. };
  54604. // Clone
  54605. /**
  54606. * Clones the particle system.
  54607. * @param name The name of the cloned object
  54608. * @param newEmitter The new emitter to use
  54609. * @returns the cloned particle system
  54610. */
  54611. ParticleSystem.prototype.clone = function (name, newEmitter) {
  54612. var custom = null;
  54613. var program = null;
  54614. if (this.customShader != null) {
  54615. program = this.customShader;
  54616. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  54617. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  54618. }
  54619. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  54620. result.customShader = program;
  54621. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  54622. if (newEmitter === undefined) {
  54623. newEmitter = this.emitter;
  54624. }
  54625. result.emitter = newEmitter;
  54626. if (this.particleTexture) {
  54627. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  54628. }
  54629. if (!this.preventAutoStart) {
  54630. result.start();
  54631. }
  54632. return result;
  54633. };
  54634. /**
  54635. * Serializes the particle system to a JSON object.
  54636. * @returns the JSON object
  54637. */
  54638. ParticleSystem.prototype.serialize = function () {
  54639. var serializationObject = {};
  54640. serializationObject.name = this.name;
  54641. serializationObject.id = this.id;
  54642. // Emitter
  54643. if (this.emitter.position) {
  54644. var emitterMesh = this.emitter;
  54645. serializationObject.emitterId = emitterMesh.id;
  54646. }
  54647. else {
  54648. var emitterPosition = this.emitter;
  54649. serializationObject.emitter = emitterPosition.asArray();
  54650. }
  54651. serializationObject.capacity = this.getCapacity();
  54652. if (this.particleTexture) {
  54653. serializationObject.textureName = this.particleTexture.name;
  54654. }
  54655. // Animations
  54656. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  54657. // Particle system
  54658. serializationObject.minAngularSpeed = this.minAngularSpeed;
  54659. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  54660. serializationObject.minSize = this.minSize;
  54661. serializationObject.maxSize = this.maxSize;
  54662. serializationObject.minEmitPower = this.minEmitPower;
  54663. serializationObject.maxEmitPower = this.maxEmitPower;
  54664. serializationObject.minLifeTime = this.minLifeTime;
  54665. serializationObject.maxLifeTime = this.maxLifeTime;
  54666. serializationObject.emitRate = this.emitRate;
  54667. serializationObject.minEmitBox = this.minEmitBox.asArray();
  54668. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  54669. serializationObject.gravity = this.gravity.asArray();
  54670. serializationObject.direction1 = this.direction1.asArray();
  54671. serializationObject.direction2 = this.direction2.asArray();
  54672. serializationObject.color1 = this.color1.asArray();
  54673. serializationObject.color2 = this.color2.asArray();
  54674. serializationObject.colorDead = this.colorDead.asArray();
  54675. serializationObject.updateSpeed = this.updateSpeed;
  54676. serializationObject.targetStopDuration = this.targetStopDuration;
  54677. serializationObject.textureMask = this.textureMask.asArray();
  54678. serializationObject.blendMode = this.blendMode;
  54679. serializationObject.customShader = this.customShader;
  54680. serializationObject.preventAutoStart = this.preventAutoStart;
  54681. serializationObject.startSpriteCellID = this.startSpriteCellID;
  54682. serializationObject.endSpriteCellID = this.endSpriteCellID;
  54683. serializationObject.spriteCellLoop = this.spriteCellLoop;
  54684. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  54685. serializationObject.spriteCellWidth = this.spriteCellWidth;
  54686. serializationObject.spriteCellHeight = this.spriteCellHeight;
  54687. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  54688. // Emitter
  54689. if (this.particleEmitterType) {
  54690. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  54691. }
  54692. return serializationObject;
  54693. };
  54694. /**
  54695. * Parses a JSON object to create a particle system.
  54696. * @param parsedParticleSystem The JSON object to parse
  54697. * @param scene The scene to create the particle system in
  54698. * @param rootUrl The root url to use to load external dependencies like texture
  54699. * @returns the Parsed particle system
  54700. */
  54701. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  54702. var name = parsedParticleSystem.name;
  54703. var custom = null;
  54704. var program = null;
  54705. if (parsedParticleSystem.customShader) {
  54706. program = parsedParticleSystem.customShader;
  54707. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  54708. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  54709. }
  54710. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  54711. particleSystem.customShader = program;
  54712. if (parsedParticleSystem.id) {
  54713. particleSystem.id = parsedParticleSystem.id;
  54714. }
  54715. // Auto start
  54716. if (parsedParticleSystem.preventAutoStart) {
  54717. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  54718. }
  54719. // Texture
  54720. if (parsedParticleSystem.textureName) {
  54721. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  54722. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  54723. }
  54724. // Emitter
  54725. if (parsedParticleSystem.emitterId) {
  54726. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  54727. }
  54728. else {
  54729. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  54730. }
  54731. // Animations
  54732. if (parsedParticleSystem.animations) {
  54733. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  54734. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  54735. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  54736. }
  54737. }
  54738. if (parsedParticleSystem.autoAnimate) {
  54739. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  54740. }
  54741. // Particle system
  54742. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  54743. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  54744. particleSystem.minSize = parsedParticleSystem.minSize;
  54745. particleSystem.maxSize = parsedParticleSystem.maxSize;
  54746. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  54747. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  54748. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  54749. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  54750. particleSystem.emitRate = parsedParticleSystem.emitRate;
  54751. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  54752. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  54753. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  54754. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  54755. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  54756. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  54757. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  54758. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  54759. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  54760. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  54761. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  54762. particleSystem.blendMode = parsedParticleSystem.blendMode;
  54763. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  54764. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  54765. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  54766. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  54767. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  54768. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  54769. if (!particleSystem.preventAutoStart) {
  54770. particleSystem.start();
  54771. }
  54772. return particleSystem;
  54773. };
  54774. /**
  54775. * Source color is added to the destination color without alpha affecting the result.
  54776. */
  54777. ParticleSystem.BLENDMODE_ONEONE = 0;
  54778. /**
  54779. * Blend current color and particle color using particle’s alpha.
  54780. */
  54781. ParticleSystem.BLENDMODE_STANDARD = 1;
  54782. return ParticleSystem;
  54783. }());
  54784. BABYLON.ParticleSystem = ParticleSystem;
  54785. })(BABYLON || (BABYLON = {}));
  54786. //# sourceMappingURL=babylon.particleSystem.js.map
  54787. "use strict";
  54788. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  54789. "use strict";
  54790. var BABYLON;
  54791. (function (BABYLON) {
  54792. /**
  54793. * Particle emitter emitting particles from the inside of a box.
  54794. * It emits the particles randomly between 2 given directions.
  54795. */
  54796. var BoxParticleEmitter = /** @class */ (function () {
  54797. /**
  54798. * Creates a new instance BoxParticleEmitter
  54799. */
  54800. function BoxParticleEmitter() {
  54801. /**
  54802. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  54803. */
  54804. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  54805. /**
  54806. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  54807. */
  54808. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  54809. /**
  54810. * 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.
  54811. */
  54812. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  54813. /**
  54814. * 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.
  54815. */
  54816. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  54817. }
  54818. /**
  54819. * Called by the particle System when the direction is computed for the created particle.
  54820. * @param emitPower is the power of the particle (speed)
  54821. * @param worldMatrix is the world matrix of the particle system
  54822. * @param directionToUpdate is the direction vector to update with the result
  54823. * @param particle is the particle we are computed the direction for
  54824. */
  54825. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  54826. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  54827. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  54828. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  54829. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  54830. };
  54831. /**
  54832. * Called by the particle System when the position is computed for the created particle.
  54833. * @param worldMatrix is the world matrix of the particle system
  54834. * @param positionToUpdate is the position vector to update with the result
  54835. * @param particle is the particle we are computed the position for
  54836. */
  54837. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  54838. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  54839. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  54840. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  54841. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  54842. };
  54843. /**
  54844. * Clones the current emitter and returns a copy of it
  54845. * @returns the new emitter
  54846. */
  54847. BoxParticleEmitter.prototype.clone = function () {
  54848. var newOne = new BoxParticleEmitter();
  54849. BABYLON.Tools.DeepCopy(this, newOne);
  54850. return newOne;
  54851. };
  54852. /**
  54853. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  54854. * @param effect defines the update shader
  54855. */
  54856. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  54857. effect.setVector3("direction1", this.direction1);
  54858. effect.setVector3("direction2", this.direction2);
  54859. effect.setVector3("minEmitBox", this.minEmitBox);
  54860. effect.setVector3("maxEmitBox", this.maxEmitBox);
  54861. };
  54862. /**
  54863. * Returns a string to use to update the GPU particles update shader
  54864. * @returns a string containng the defines string
  54865. */
  54866. BoxParticleEmitter.prototype.getEffectDefines = function () {
  54867. return "#define BOXEMITTER";
  54868. };
  54869. /**
  54870. * Returns the string "BoxEmitter"
  54871. * @returns a string containing the class name
  54872. */
  54873. BoxParticleEmitter.prototype.getClassName = function () {
  54874. return "BoxEmitter";
  54875. };
  54876. /**
  54877. * Serializes the particle system to a JSON object.
  54878. * @returns the JSON object
  54879. */
  54880. BoxParticleEmitter.prototype.serialize = function () {
  54881. var serializationObject = {};
  54882. serializationObject.type = this.getClassName();
  54883. serializationObject.direction1 = this.direction1.asArray();
  54884. ;
  54885. serializationObject.direction2 = this.direction2.asArray();
  54886. ;
  54887. serializationObject.minEmitBox = this.minEmitBox.asArray();
  54888. ;
  54889. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  54890. ;
  54891. return serializationObject;
  54892. };
  54893. /**
  54894. * Parse properties from a JSON object
  54895. * @param serializationObject defines the JSON object
  54896. */
  54897. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  54898. this.direction1.copyFrom(serializationObject.direction1);
  54899. this.direction2.copyFrom(serializationObject.direction2);
  54900. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  54901. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  54902. };
  54903. return BoxParticleEmitter;
  54904. }());
  54905. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  54906. })(BABYLON || (BABYLON = {}));
  54907. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  54908. "use strict";
  54909. var BABYLON;
  54910. (function (BABYLON) {
  54911. /**
  54912. * Particle emitter emitting particles from the inside of a cone.
  54913. * It emits the particles alongside the cone volume from the base to the particle.
  54914. * The emission direction might be randomized.
  54915. */
  54916. var ConeParticleEmitter = /** @class */ (function () {
  54917. /**
  54918. * Creates a new instance ConeParticleEmitter
  54919. * @param radius the radius of the emission cone (1 by default)
  54920. * @param angles the cone base angle (PI by default)
  54921. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  54922. */
  54923. function ConeParticleEmitter(radius,
  54924. /**
  54925. * The radius of the emission cone.
  54926. */
  54927. angle,
  54928. /**
  54929. * The cone base angle.
  54930. */
  54931. directionRandomizer) {
  54932. if (radius === void 0) { radius = 1; }
  54933. if (angle === void 0) { angle = Math.PI; }
  54934. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  54935. this.angle = angle;
  54936. this.directionRandomizer = directionRandomizer;
  54937. this.radius = radius;
  54938. }
  54939. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  54940. /**
  54941. * Gets the radius of the emission cone.
  54942. */
  54943. get: function () {
  54944. return this._radius;
  54945. },
  54946. /**
  54947. * Sets the radius of the emission cone.
  54948. */
  54949. set: function (value) {
  54950. this._radius = value;
  54951. if (this.angle !== 0) {
  54952. this._height = value / Math.tan(this.angle / 2);
  54953. }
  54954. else {
  54955. this._height = 1;
  54956. }
  54957. },
  54958. enumerable: true,
  54959. configurable: true
  54960. });
  54961. /**
  54962. * Called by the particle System when the direction is computed for the created particle.
  54963. * @param emitPower is the power of the particle (speed)
  54964. * @param worldMatrix is the world matrix of the particle system
  54965. * @param directionToUpdate is the direction vector to update with the result
  54966. * @param particle is the particle we are computed the direction for
  54967. */
  54968. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  54969. if (this.angle === 0) {
  54970. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  54971. }
  54972. else {
  54973. // measure the direction Vector from the emitter to the particle.
  54974. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  54975. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  54976. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  54977. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  54978. direction.x += randX;
  54979. direction.y += randY;
  54980. direction.z += randZ;
  54981. direction.normalize();
  54982. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  54983. }
  54984. };
  54985. /**
  54986. * Called by the particle System when the position is computed for the created particle.
  54987. * @param worldMatrix is the world matrix of the particle system
  54988. * @param positionToUpdate is the position vector to update with the result
  54989. * @param particle is the particle we are computed the position for
  54990. */
  54991. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  54992. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  54993. var h = BABYLON.Scalar.RandomRange(0, 1);
  54994. // Better distribution in a cone at normal angles.
  54995. h = 1 - h * h;
  54996. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  54997. radius = radius * h;
  54998. var randX = radius * Math.sin(s);
  54999. var randZ = radius * Math.cos(s);
  55000. var randY = h * this._height;
  55001. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  55002. };
  55003. /**
  55004. * Clones the current emitter and returns a copy of it
  55005. * @returns the new emitter
  55006. */
  55007. ConeParticleEmitter.prototype.clone = function () {
  55008. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  55009. BABYLON.Tools.DeepCopy(this, newOne);
  55010. return newOne;
  55011. };
  55012. /**
  55013. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  55014. * @param effect defines the update shader
  55015. */
  55016. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  55017. effect.setFloat("radius", this.radius);
  55018. effect.setFloat("angle", this.angle);
  55019. effect.setFloat("height", this._height);
  55020. effect.setFloat("directionRandomizer", this.directionRandomizer);
  55021. };
  55022. /**
  55023. * Returns a string to use to update the GPU particles update shader
  55024. * @returns a string containng the defines string
  55025. */
  55026. ConeParticleEmitter.prototype.getEffectDefines = function () {
  55027. return "#define CONEEMITTER";
  55028. };
  55029. /**
  55030. * Returns the string "BoxEmitter"
  55031. * @returns a string containing the class name
  55032. */
  55033. ConeParticleEmitter.prototype.getClassName = function () {
  55034. return "ConeEmitter";
  55035. };
  55036. /**
  55037. * Serializes the particle system to a JSON object.
  55038. * @returns the JSON object
  55039. */
  55040. ConeParticleEmitter.prototype.serialize = function () {
  55041. var serializationObject = {};
  55042. serializationObject.type = this.getClassName();
  55043. serializationObject.radius = this.radius;
  55044. serializationObject.angle = this.angle;
  55045. serializationObject.directionRandomizer = this.directionRandomizer;
  55046. return serializationObject;
  55047. };
  55048. /**
  55049. * Parse properties from a JSON object
  55050. * @param serializationObject defines the JSON object
  55051. */
  55052. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  55053. this.radius = serializationObject.radius;
  55054. this.angle = serializationObject.angle;
  55055. this.directionRandomizer = serializationObject.directionRandomizer;
  55056. };
  55057. return ConeParticleEmitter;
  55058. }());
  55059. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  55060. })(BABYLON || (BABYLON = {}));
  55061. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  55062. "use strict";
  55063. var BABYLON;
  55064. (function (BABYLON) {
  55065. /**
  55066. * Particle emitter emitting particles from the inside of a sphere.
  55067. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  55068. */
  55069. var SphereParticleEmitter = /** @class */ (function () {
  55070. /**
  55071. * Creates a new instance SphereParticleEmitter
  55072. * @param radius the radius of the emission sphere (1 by default)
  55073. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  55074. */
  55075. function SphereParticleEmitter(
  55076. /**
  55077. * The radius of the emission sphere.
  55078. */
  55079. radius,
  55080. /**
  55081. * How much to randomize the particle direction [0-1].
  55082. */
  55083. directionRandomizer) {
  55084. if (radius === void 0) { radius = 1; }
  55085. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  55086. this.radius = radius;
  55087. this.directionRandomizer = directionRandomizer;
  55088. }
  55089. /**
  55090. * Called by the particle System when the direction is computed for the created particle.
  55091. * @param emitPower is the power of the particle (speed)
  55092. * @param worldMatrix is the world matrix of the particle system
  55093. * @param directionToUpdate is the direction vector to update with the result
  55094. * @param particle is the particle we are computed the direction for
  55095. */
  55096. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  55097. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  55098. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  55099. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  55100. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  55101. direction.x += randX;
  55102. direction.y += randY;
  55103. direction.z += randZ;
  55104. direction.normalize();
  55105. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  55106. };
  55107. /**
  55108. * Called by the particle System when the position is computed for the created particle.
  55109. * @param worldMatrix is the world matrix of the particle system
  55110. * @param positionToUpdate is the position vector to update with the result
  55111. * @param particle is the particle we are computed the position for
  55112. */
  55113. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  55114. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  55115. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  55116. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  55117. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  55118. var randY = randRadius * Math.cos(theta);
  55119. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  55120. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  55121. };
  55122. /**
  55123. * Clones the current emitter and returns a copy of it
  55124. * @returns the new emitter
  55125. */
  55126. SphereParticleEmitter.prototype.clone = function () {
  55127. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  55128. BABYLON.Tools.DeepCopy(this, newOne);
  55129. return newOne;
  55130. };
  55131. /**
  55132. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  55133. * @param effect defines the update shader
  55134. */
  55135. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  55136. effect.setFloat("radius", this.radius);
  55137. effect.setFloat("directionRandomizer", this.directionRandomizer);
  55138. };
  55139. /**
  55140. * Returns a string to use to update the GPU particles update shader
  55141. * @returns a string containng the defines string
  55142. */
  55143. SphereParticleEmitter.prototype.getEffectDefines = function () {
  55144. return "#define SPHEREEMITTER";
  55145. };
  55146. /**
  55147. * Returns the string "SphereParticleEmitter"
  55148. * @returns a string containing the class name
  55149. */
  55150. SphereParticleEmitter.prototype.getClassName = function () {
  55151. return "SphereParticleEmitter";
  55152. };
  55153. /**
  55154. * Serializes the particle system to a JSON object.
  55155. * @returns the JSON object
  55156. */
  55157. SphereParticleEmitter.prototype.serialize = function () {
  55158. var serializationObject = {};
  55159. serializationObject.type = this.getClassName();
  55160. serializationObject.radius = this.radius;
  55161. serializationObject.directionRandomizer = this.directionRandomizer;
  55162. return serializationObject;
  55163. };
  55164. /**
  55165. * Parse properties from a JSON object
  55166. * @param serializationObject defines the JSON object
  55167. */
  55168. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  55169. this.radius = serializationObject.radius;
  55170. this.directionRandomizer = serializationObject.directionRandomizer;
  55171. };
  55172. return SphereParticleEmitter;
  55173. }());
  55174. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  55175. /**
  55176. * Particle emitter emitting particles from the inside of a sphere.
  55177. * It emits the particles randomly between two vectors.
  55178. */
  55179. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  55180. __extends(SphereDirectedParticleEmitter, _super);
  55181. /**
  55182. * Creates a new instance SphereDirectedParticleEmitter
  55183. * @param radius the radius of the emission sphere (1 by default)
  55184. * @param direction1 the min limit of the emission direction (up vector by default)
  55185. * @param direction2 the max limit of the emission direction (up vector by default)
  55186. */
  55187. function SphereDirectedParticleEmitter(radius,
  55188. /**
  55189. * The min limit of the emission direction.
  55190. */
  55191. direction1,
  55192. /**
  55193. * The max limit of the emission direction.
  55194. */
  55195. direction2) {
  55196. if (radius === void 0) { radius = 1; }
  55197. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  55198. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  55199. var _this = _super.call(this, radius) || this;
  55200. _this.direction1 = direction1;
  55201. _this.direction2 = direction2;
  55202. return _this;
  55203. }
  55204. /**
  55205. * Called by the particle System when the direction is computed for the created particle.
  55206. * @param emitPower is the power of the particle (speed)
  55207. * @param worldMatrix is the world matrix of the particle system
  55208. * @param directionToUpdate is the direction vector to update with the result
  55209. * @param particle is the particle we are computed the direction for
  55210. */
  55211. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  55212. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  55213. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  55214. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  55215. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  55216. };
  55217. /**
  55218. * Clones the current emitter and returns a copy of it
  55219. * @returns the new emitter
  55220. */
  55221. SphereDirectedParticleEmitter.prototype.clone = function () {
  55222. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  55223. BABYLON.Tools.DeepCopy(this, newOne);
  55224. return newOne;
  55225. };
  55226. /**
  55227. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  55228. * @param effect defines the update shader
  55229. */
  55230. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  55231. effect.setFloat("radius", this.radius);
  55232. effect.setVector3("direction1", this.direction1);
  55233. effect.setVector3("direction2", this.direction2);
  55234. };
  55235. /**
  55236. * Returns a string to use to update the GPU particles update shader
  55237. * @returns a string containng the defines string
  55238. */
  55239. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  55240. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  55241. };
  55242. /**
  55243. * Returns the string "SphereDirectedParticleEmitter"
  55244. * @returns a string containing the class name
  55245. */
  55246. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  55247. return "SphereDirectedParticleEmitter";
  55248. };
  55249. /**
  55250. * Serializes the particle system to a JSON object.
  55251. * @returns the JSON object
  55252. */
  55253. SphereDirectedParticleEmitter.prototype.serialize = function () {
  55254. var serializationObject = _super.prototype.serialize.call(this);
  55255. ;
  55256. serializationObject.direction1 = this.direction1.asArray();
  55257. ;
  55258. serializationObject.direction2 = this.direction2.asArray();
  55259. ;
  55260. return serializationObject;
  55261. };
  55262. /**
  55263. * Parse properties from a JSON object
  55264. * @param serializationObject defines the JSON object
  55265. */
  55266. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  55267. _super.prototype.parse.call(this, serializationObject);
  55268. this.direction1.copyFrom(serializationObject.direction1);
  55269. this.direction2.copyFrom(serializationObject.direction2);
  55270. };
  55271. return SphereDirectedParticleEmitter;
  55272. }(SphereParticleEmitter));
  55273. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  55274. })(BABYLON || (BABYLON = {}));
  55275. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  55276. "use strict";
  55277. var __assign = (this && this.__assign) || Object.assign || function(t) {
  55278. for (var s, i = 1, n = arguments.length; i < n; i++) {
  55279. s = arguments[i];
  55280. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  55281. t[p] = s[p];
  55282. }
  55283. return t;
  55284. };
  55285. var BABYLON;
  55286. (function (BABYLON) {
  55287. /**
  55288. * This represents a GPU particle system in Babylon
  55289. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  55290. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  55291. */
  55292. var GPUParticleSystem = /** @class */ (function () {
  55293. /**
  55294. * Instantiates a GPU particle system.
  55295. * 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.
  55296. * @param name The name of the particle system
  55297. * @param capacity The max number of particles alive at the same time
  55298. * @param scene The scene the particle system belongs to
  55299. */
  55300. function GPUParticleSystem(name, options, scene) {
  55301. /**
  55302. * The emitter represents the Mesh or position we are attaching the particle system to.
  55303. */
  55304. this.emitter = null;
  55305. /**
  55306. * The rendering group used by the Particle system to chose when to render.
  55307. */
  55308. this.renderingGroupId = 0;
  55309. /**
  55310. * The layer mask we are rendering the particles through.
  55311. */
  55312. this.layerMask = 0x0FFFFFFF;
  55313. this._targetIndex = 0;
  55314. this._currentRenderId = -1;
  55315. this._started = false;
  55316. this._stopped = false;
  55317. this._timeDelta = 0;
  55318. this._attributesStrideSize = 14;
  55319. this._actualFrame = 0;
  55320. /**
  55321. * List of animations used by the particle system.
  55322. */
  55323. this.animations = [];
  55324. /**
  55325. * An event triggered when the system is disposed.
  55326. */
  55327. this.onDisposeObservable = new BABYLON.Observable();
  55328. /**
  55329. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55330. */
  55331. this.updateSpeed = 0.01;
  55332. /**
  55333. * The amount of time the particle system is running (depends of the overall update speed).
  55334. */
  55335. this.targetStopDuration = 0;
  55336. /**
  55337. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55338. */
  55339. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  55340. /**
  55341. * Minimum life time of emitting particles.
  55342. */
  55343. this.minLifeTime = 1;
  55344. /**
  55345. * Maximum life time of emitting particles.
  55346. */
  55347. this.maxLifeTime = 1;
  55348. /**
  55349. * Minimum Size of emitting particles.
  55350. */
  55351. this.minSize = 1;
  55352. /**
  55353. * Maximum Size of emitting particles.
  55354. */
  55355. this.maxSize = 1;
  55356. /**
  55357. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55358. */
  55359. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55360. /**
  55361. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55362. */
  55363. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55364. /**
  55365. * Color the particle will have at the end of its lifetime.
  55366. */
  55367. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  55368. /**
  55369. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  55370. */
  55371. this.emitRate = 100;
  55372. /**
  55373. * You can use gravity if you want to give an orientation to your particles.
  55374. */
  55375. this.gravity = BABYLON.Vector3.Zero();
  55376. /**
  55377. * Minimum power of emitting particles.
  55378. */
  55379. this.minEmitPower = 1;
  55380. /**
  55381. * Maximum power of emitting particles.
  55382. */
  55383. this.maxEmitPower = 1;
  55384. /**
  55385. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55386. * to override the particles.
  55387. */
  55388. this.forceDepthWrite = false;
  55389. this.id = name;
  55390. this.name = name;
  55391. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55392. this._engine = this._scene.getEngine();
  55393. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  55394. this._capacity = fullOptions.capacity;
  55395. this._activeCount = fullOptions.capacity;
  55396. this._currentActiveCount = 0;
  55397. this._scene.particleSystems.push(this);
  55398. this._updateEffectOptions = {
  55399. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  55400. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  55401. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  55402. uniformBuffersNames: [],
  55403. samplers: ["randomSampler"],
  55404. defines: "",
  55405. fallbacks: null,
  55406. onCompiled: null,
  55407. onError: null,
  55408. indexParameters: null,
  55409. maxSimultaneousLights: 0,
  55410. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  55411. };
  55412. // Random data
  55413. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  55414. var d = [];
  55415. for (var i = 0; i < maxTextureSize; ++i) {
  55416. d.push(Math.random());
  55417. d.push(Math.random());
  55418. d.push(Math.random());
  55419. d.push(Math.random());
  55420. }
  55421. 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);
  55422. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  55423. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  55424. this._randomTextureSize = maxTextureSize;
  55425. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55426. }
  55427. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  55428. /**
  55429. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  55430. */
  55431. get: function () {
  55432. if (!BABYLON.Engine.LastCreatedEngine) {
  55433. return false;
  55434. }
  55435. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  55436. },
  55437. enumerable: true,
  55438. configurable: true
  55439. });
  55440. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  55441. /**
  55442. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55443. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55444. */
  55445. get: function () {
  55446. if (this.particleEmitterType.direction1) {
  55447. return this.particleEmitterType.direction1;
  55448. }
  55449. return BABYLON.Vector3.Zero();
  55450. },
  55451. set: function (value) {
  55452. if (this.particleEmitterType.direction1) {
  55453. this.particleEmitterType.direction1 = value;
  55454. }
  55455. },
  55456. enumerable: true,
  55457. configurable: true
  55458. });
  55459. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  55460. /**
  55461. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55462. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55463. */
  55464. get: function () {
  55465. if (this.particleEmitterType.direction2) {
  55466. return this.particleEmitterType.direction2;
  55467. }
  55468. return BABYLON.Vector3.Zero();
  55469. },
  55470. set: function (value) {
  55471. if (this.particleEmitterType.direction2) {
  55472. this.particleEmitterType.direction2 = value;
  55473. }
  55474. },
  55475. enumerable: true,
  55476. configurable: true
  55477. });
  55478. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  55479. /**
  55480. * 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.
  55481. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55482. */
  55483. get: function () {
  55484. if (this.particleEmitterType.minEmitBox) {
  55485. return this.particleEmitterType.minEmitBox;
  55486. }
  55487. return BABYLON.Vector3.Zero();
  55488. },
  55489. set: function (value) {
  55490. if (this.particleEmitterType.minEmitBox) {
  55491. this.particleEmitterType.minEmitBox = value;
  55492. }
  55493. },
  55494. enumerable: true,
  55495. configurable: true
  55496. });
  55497. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  55498. /**
  55499. * 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.
  55500. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55501. */
  55502. get: function () {
  55503. if (this.particleEmitterType.maxEmitBox) {
  55504. return this.particleEmitterType.maxEmitBox;
  55505. }
  55506. return BABYLON.Vector3.Zero();
  55507. },
  55508. set: function (value) {
  55509. if (this.particleEmitterType.maxEmitBox) {
  55510. this.particleEmitterType.maxEmitBox = value;
  55511. }
  55512. },
  55513. enumerable: true,
  55514. configurable: true
  55515. });
  55516. /**
  55517. * Gets the maximum number of particles active at the same time.
  55518. * @returns The max number of active particles.
  55519. */
  55520. GPUParticleSystem.prototype.getCapacity = function () {
  55521. return this._capacity;
  55522. };
  55523. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  55524. /**
  55525. * Gets or set the number of active particles
  55526. */
  55527. get: function () {
  55528. return this._activeCount;
  55529. },
  55530. set: function (value) {
  55531. this._activeCount = Math.min(value, this._capacity);
  55532. },
  55533. enumerable: true,
  55534. configurable: true
  55535. });
  55536. /**
  55537. * Is this system ready to be used/rendered
  55538. * @return true if the system is ready
  55539. */
  55540. GPUParticleSystem.prototype.isReady = function () {
  55541. if (!this._updateEffect) {
  55542. this._recreateUpdateEffect();
  55543. this._recreateRenderEffect();
  55544. return false;
  55545. }
  55546. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  55547. return false;
  55548. }
  55549. return true;
  55550. };
  55551. /**
  55552. * Gets Wether the system has been started.
  55553. * @returns True if it has been started, otherwise false.
  55554. */
  55555. GPUParticleSystem.prototype.isStarted = function () {
  55556. return this._started;
  55557. };
  55558. /**
  55559. * Starts the particle system and begins to emit.
  55560. */
  55561. GPUParticleSystem.prototype.start = function () {
  55562. this._started = true;
  55563. this._stopped = false;
  55564. };
  55565. /**
  55566. * Stops the particle system.
  55567. */
  55568. GPUParticleSystem.prototype.stop = function () {
  55569. this._stopped = true;
  55570. };
  55571. /**
  55572. * Remove all active particles
  55573. */
  55574. GPUParticleSystem.prototype.reset = function () {
  55575. this._releaseBuffers();
  55576. this._releaseVAOs();
  55577. this._currentActiveCount = 0;
  55578. this._targetIndex = 0;
  55579. };
  55580. /**
  55581. * Returns the string "GPUParticleSystem"
  55582. * @returns a string containing the class name
  55583. */
  55584. GPUParticleSystem.prototype.getClassName = function () {
  55585. return "GPUParticleSystem";
  55586. };
  55587. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  55588. var updateVertexBuffers = {};
  55589. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  55590. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  55591. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  55592. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  55593. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  55594. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  55595. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  55596. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  55597. this._engine.bindArrayBuffer(null);
  55598. return vao;
  55599. };
  55600. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  55601. var renderVertexBuffers = {};
  55602. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  55603. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  55604. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  55605. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  55606. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  55607. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  55608. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  55609. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  55610. this._engine.bindArrayBuffer(null);
  55611. return vao;
  55612. };
  55613. GPUParticleSystem.prototype._initialize = function (force) {
  55614. if (force === void 0) { force = false; }
  55615. if (this._buffer0 && !force) {
  55616. return;
  55617. }
  55618. var engine = this._scene.getEngine();
  55619. var data = new Array();
  55620. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  55621. // position
  55622. data.push(0.0);
  55623. data.push(0.0);
  55624. data.push(0.0);
  55625. // Age and life
  55626. data.push(0.0); // create the particle as a dead one to create a new one at start
  55627. data.push(0.0);
  55628. // Seed
  55629. data.push(Math.random());
  55630. // Size
  55631. data.push(0.0);
  55632. // color
  55633. data.push(0.0);
  55634. data.push(0.0);
  55635. data.push(0.0);
  55636. data.push(0.0);
  55637. // direction
  55638. data.push(0.0);
  55639. data.push(0.0);
  55640. data.push(0.0);
  55641. }
  55642. // Sprite data
  55643. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  55644. -0.5, 0.5, 0, 1,
  55645. -0.5, -0.5, 0, 0,
  55646. 0.5, -0.5, 1, 0]);
  55647. // Buffers
  55648. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  55649. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  55650. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  55651. // Update VAO
  55652. this._updateVAO = [];
  55653. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  55654. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  55655. // Render VAO
  55656. this._renderVAO = [];
  55657. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  55658. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  55659. // Links
  55660. this._sourceBuffer = this._buffer0;
  55661. this._targetBuffer = this._buffer1;
  55662. };
  55663. /** @ignore */
  55664. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  55665. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  55666. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  55667. return;
  55668. }
  55669. this._updateEffectOptions.defines = defines;
  55670. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  55671. };
  55672. /** @ignore */
  55673. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  55674. var defines = "";
  55675. if (this._scene.clipPlane) {
  55676. defines = "\n#define CLIPPLANE";
  55677. }
  55678. if (this._renderEffect && this._renderEffect.defines === defines) {
  55679. return;
  55680. }
  55681. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  55682. };
  55683. /**
  55684. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  55685. */
  55686. GPUParticleSystem.prototype.animate = function () {
  55687. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  55688. this._actualFrame += this._timeDelta;
  55689. if (!this._stopped) {
  55690. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  55691. this.stop();
  55692. }
  55693. }
  55694. };
  55695. /**
  55696. * Renders the particle system in its current state.
  55697. * @returns the current number of particles
  55698. */
  55699. GPUParticleSystem.prototype.render = function () {
  55700. if (!this._started) {
  55701. return 0;
  55702. }
  55703. this._recreateUpdateEffect();
  55704. this._recreateRenderEffect();
  55705. if (!this.isReady()) {
  55706. return 0;
  55707. }
  55708. if (this._currentRenderId === this._scene.getRenderId()) {
  55709. return 0;
  55710. }
  55711. this._currentRenderId = this._scene.getRenderId();
  55712. // Get everything ready to render
  55713. this._initialize();
  55714. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  55715. // Enable update effect
  55716. this._engine.enableEffect(this._updateEffect);
  55717. this._engine.setState(false);
  55718. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  55719. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  55720. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  55721. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  55722. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  55723. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  55724. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  55725. this._updateEffect.setDirectColor4("color1", this.color1);
  55726. this._updateEffect.setDirectColor4("color2", this.color2);
  55727. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  55728. this._updateEffect.setVector3("gravity", this.gravity);
  55729. if (this.particleEmitterType) {
  55730. this.particleEmitterType.applyToShader(this._updateEffect);
  55731. }
  55732. var emitterWM;
  55733. if (this.emitter.position) {
  55734. var emitterMesh = this.emitter;
  55735. emitterWM = emitterMesh.getWorldMatrix();
  55736. }
  55737. else {
  55738. var emitterPosition = this.emitter;
  55739. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  55740. }
  55741. this._updateEffect.setMatrix("emitterWM", emitterWM);
  55742. // Bind source VAO
  55743. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  55744. // Update
  55745. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  55746. this._engine.setRasterizerState(false);
  55747. this._engine.beginTransformFeedback();
  55748. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  55749. this._engine.endTransformFeedback();
  55750. this._engine.setRasterizerState(true);
  55751. this._engine.bindTransformFeedbackBuffer(null);
  55752. // Enable render effect
  55753. this._engine.enableEffect(this._renderEffect);
  55754. var viewMatrix = this._scene.getViewMatrix();
  55755. this._renderEffect.setMatrix("view", viewMatrix);
  55756. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  55757. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  55758. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  55759. if (this._scene.clipPlane) {
  55760. var clipPlane = this._scene.clipPlane;
  55761. var invView = viewMatrix.clone();
  55762. invView.invert();
  55763. this._renderEffect.setMatrix("invView", invView);
  55764. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  55765. }
  55766. // Draw order
  55767. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  55768. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  55769. }
  55770. else {
  55771. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  55772. }
  55773. if (this.forceDepthWrite) {
  55774. this._engine.setDepthWrite(true);
  55775. }
  55776. // Bind source VAO
  55777. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  55778. // Render
  55779. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  55780. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  55781. // Switch VAOs
  55782. this._targetIndex++;
  55783. if (this._targetIndex === 2) {
  55784. this._targetIndex = 0;
  55785. }
  55786. // Switch buffers
  55787. var tmpBuffer = this._sourceBuffer;
  55788. this._sourceBuffer = this._targetBuffer;
  55789. this._targetBuffer = tmpBuffer;
  55790. return this._currentActiveCount;
  55791. };
  55792. /**
  55793. * Rebuilds the particle system
  55794. */
  55795. GPUParticleSystem.prototype.rebuild = function () {
  55796. this._initialize(true);
  55797. };
  55798. GPUParticleSystem.prototype._releaseBuffers = function () {
  55799. if (this._buffer0) {
  55800. this._buffer0.dispose();
  55801. this._buffer0 = null;
  55802. }
  55803. if (this._buffer1) {
  55804. this._buffer1.dispose();
  55805. this._buffer1 = null;
  55806. }
  55807. if (this._spriteBuffer) {
  55808. this._spriteBuffer.dispose();
  55809. this._spriteBuffer = null;
  55810. }
  55811. };
  55812. GPUParticleSystem.prototype._releaseVAOs = function () {
  55813. if (!this._updateVAO) {
  55814. return;
  55815. }
  55816. for (var index = 0; index < this._updateVAO.length; index++) {
  55817. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  55818. }
  55819. this._updateVAO = [];
  55820. for (var index = 0; index < this._renderVAO.length; index++) {
  55821. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  55822. }
  55823. this._renderVAO = [];
  55824. };
  55825. /**
  55826. * Disposes the particle system and free the associated resources
  55827. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  55828. */
  55829. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  55830. if (disposeTexture === void 0) { disposeTexture = true; }
  55831. var index = this._scene.particleSystems.indexOf(this);
  55832. if (index > -1) {
  55833. this._scene.particleSystems.splice(index, 1);
  55834. }
  55835. this._releaseBuffers();
  55836. this._releaseVAOs();
  55837. if (this._randomTexture) {
  55838. this._randomTexture.dispose();
  55839. this._randomTexture = null;
  55840. }
  55841. if (disposeTexture && this.particleTexture) {
  55842. this.particleTexture.dispose();
  55843. this.particleTexture = null;
  55844. }
  55845. // Callback
  55846. this.onDisposeObservable.notifyObservers(this);
  55847. this.onDisposeObservable.clear();
  55848. };
  55849. /**
  55850. * Clones the particle system.
  55851. * @param name The name of the cloned object
  55852. * @param newEmitter The new emitter to use
  55853. * @returns the cloned particle system
  55854. */
  55855. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  55856. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  55857. BABYLON.Tools.DeepCopy(this, result);
  55858. if (newEmitter === undefined) {
  55859. newEmitter = this.emitter;
  55860. }
  55861. result.emitter = newEmitter;
  55862. if (this.particleTexture) {
  55863. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  55864. }
  55865. return result;
  55866. };
  55867. /**
  55868. * Serializes the particle system to a JSON object.
  55869. * @returns the JSON object
  55870. */
  55871. GPUParticleSystem.prototype.serialize = function () {
  55872. var serializationObject = {};
  55873. serializationObject.name = this.name;
  55874. serializationObject.id = this.id;
  55875. // Emitter
  55876. if (this.emitter.position) {
  55877. var emitterMesh = this.emitter;
  55878. serializationObject.emitterId = emitterMesh.id;
  55879. }
  55880. else {
  55881. var emitterPosition = this.emitter;
  55882. serializationObject.emitter = emitterPosition.asArray();
  55883. }
  55884. serializationObject.capacity = this.getCapacity();
  55885. if (this.particleTexture) {
  55886. serializationObject.textureName = this.particleTexture.name;
  55887. }
  55888. // Animations
  55889. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  55890. // Particle system
  55891. serializationObject.activeParticleCount = this.activeParticleCount;
  55892. serializationObject.randomTextureSize = this._randomTextureSize;
  55893. serializationObject.minSize = this.minSize;
  55894. serializationObject.maxSize = this.maxSize;
  55895. serializationObject.minEmitPower = this.minEmitPower;
  55896. serializationObject.maxEmitPower = this.maxEmitPower;
  55897. serializationObject.minLifeTime = this.minLifeTime;
  55898. serializationObject.maxLifeTime = this.maxLifeTime;
  55899. serializationObject.emitRate = this.emitRate;
  55900. serializationObject.gravity = this.gravity.asArray();
  55901. serializationObject.color1 = this.color1.asArray();
  55902. serializationObject.color2 = this.color2.asArray();
  55903. serializationObject.colorDead = this.colorDead.asArray();
  55904. serializationObject.updateSpeed = this.updateSpeed;
  55905. serializationObject.targetStopDuration = this.targetStopDuration;
  55906. serializationObject.blendMode = this.blendMode;
  55907. // Emitter
  55908. if (this.particleEmitterType) {
  55909. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  55910. }
  55911. return serializationObject;
  55912. };
  55913. /**
  55914. * Parses a JSON object to create a GPU particle system.
  55915. * @param parsedParticleSystem The JSON object to parse
  55916. * @param scene The scene to create the particle system in
  55917. * @param rootUrl The root url to use to load external dependencies like texture
  55918. * @returns the parsed GPU particle system
  55919. */
  55920. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  55921. var name = parsedParticleSystem.name;
  55922. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  55923. if (parsedParticleSystem.id) {
  55924. particleSystem.id = parsedParticleSystem.id;
  55925. }
  55926. // Texture
  55927. if (parsedParticleSystem.textureName) {
  55928. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  55929. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  55930. }
  55931. // Emitter
  55932. if (parsedParticleSystem.emitterId) {
  55933. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  55934. }
  55935. else {
  55936. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  55937. }
  55938. // Animations
  55939. if (parsedParticleSystem.animations) {
  55940. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  55941. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  55942. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  55943. }
  55944. }
  55945. // Particle system
  55946. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  55947. particleSystem.minSize = parsedParticleSystem.minSize;
  55948. particleSystem.maxSize = parsedParticleSystem.maxSize;
  55949. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  55950. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  55951. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  55952. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  55953. particleSystem.emitRate = parsedParticleSystem.emitRate;
  55954. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  55955. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  55956. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  55957. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  55958. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  55959. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  55960. particleSystem.blendMode = parsedParticleSystem.blendMode;
  55961. // Emitter
  55962. if (parsedParticleSystem.particleEmitterType) {
  55963. var emitterType = void 0;
  55964. switch (parsedParticleSystem.particleEmitterType.type) {
  55965. case "SphereEmitter":
  55966. emitterType = new BABYLON.SphereParticleEmitter();
  55967. break;
  55968. case "SphereDirectedParticleEmitter":
  55969. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  55970. break;
  55971. case "ConeEmitter":
  55972. emitterType = new BABYLON.ConeParticleEmitter();
  55973. break;
  55974. case "BoxEmitter":
  55975. default:
  55976. emitterType = new BABYLON.BoxParticleEmitter();
  55977. break;
  55978. }
  55979. emitterType.parse(parsedParticleSystem.particleEmitterType);
  55980. particleSystem.particleEmitterType = emitterType;
  55981. }
  55982. return particleSystem;
  55983. };
  55984. return GPUParticleSystem;
  55985. }());
  55986. BABYLON.GPUParticleSystem = GPUParticleSystem;
  55987. })(BABYLON || (BABYLON = {}));
  55988. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  55989. "use strict";
  55990. var BABYLON;
  55991. (function (BABYLON) {
  55992. /**
  55993. * Represents one particle of a solid particle system.
  55994. */
  55995. var SolidParticle = /** @class */ (function () {
  55996. /**
  55997. * Creates a Solid Particle object.
  55998. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  55999. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  56000. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  56001. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  56002. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  56003. * @param shapeId (integer) is the model shape identifier in the SPS.
  56004. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  56005. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  56006. */
  56007. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  56008. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  56009. /**
  56010. * particle global index
  56011. */
  56012. this.idx = 0;
  56013. /**
  56014. * The color of the particle
  56015. */
  56016. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56017. /**
  56018. * The world space position of the particle.
  56019. */
  56020. this.position = BABYLON.Vector3.Zero();
  56021. /**
  56022. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  56023. */
  56024. this.rotation = BABYLON.Vector3.Zero();
  56025. /**
  56026. * The scaling of the particle.
  56027. */
  56028. this.scaling = BABYLON.Vector3.One();
  56029. /**
  56030. * The uvs of the particle.
  56031. */
  56032. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  56033. /**
  56034. * The current speed of the particle.
  56035. */
  56036. this.velocity = BABYLON.Vector3.Zero();
  56037. /**
  56038. * The pivot point in the particle local space.
  56039. */
  56040. this.pivot = BABYLON.Vector3.Zero();
  56041. /**
  56042. * Must the particle be translated from its pivot point in its local space ?
  56043. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  56044. * Default : false
  56045. */
  56046. this.translateFromPivot = false;
  56047. /**
  56048. * Is the particle active or not ?
  56049. */
  56050. this.alive = true;
  56051. /**
  56052. * Is the particle visible or not ?
  56053. */
  56054. this.isVisible = true;
  56055. /**
  56056. * Index of this particle in the global "positions" array (Internal use)
  56057. */
  56058. this._pos = 0;
  56059. /**
  56060. * Index of this particle in the global "indices" array (Internal use)
  56061. */
  56062. this._ind = 0;
  56063. /**
  56064. * ModelShape id of this particle
  56065. */
  56066. this.shapeId = 0;
  56067. /**
  56068. * Index of the particle in its shape id (Internal use)
  56069. */
  56070. this.idxInShape = 0;
  56071. /**
  56072. * Still set as invisible in order to skip useless computations (Internal use)
  56073. */
  56074. this._stillInvisible = false;
  56075. /**
  56076. * Last computed particle rotation matrix
  56077. */
  56078. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  56079. /**
  56080. * Parent particle Id, if any.
  56081. * Default null.
  56082. */
  56083. this.parentId = null;
  56084. /**
  56085. * Internal global position in the SPS.
  56086. */
  56087. this._globalPosition = BABYLON.Vector3.Zero();
  56088. this.idx = particleIndex;
  56089. this._pos = positionIndex;
  56090. this._ind = indiceIndex;
  56091. this._model = model;
  56092. this.shapeId = shapeId;
  56093. this.idxInShape = idxInShape;
  56094. this._sps = sps;
  56095. if (modelBoundingInfo) {
  56096. this._modelBoundingInfo = modelBoundingInfo;
  56097. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  56098. }
  56099. }
  56100. Object.defineProperty(SolidParticle.prototype, "scale", {
  56101. /**
  56102. * Legacy support, changed scale to scaling
  56103. */
  56104. get: function () {
  56105. return this.scaling;
  56106. },
  56107. /**
  56108. * Legacy support, changed scale to scaling
  56109. */
  56110. set: function (scale) {
  56111. this.scaling = scale;
  56112. },
  56113. enumerable: true,
  56114. configurable: true
  56115. });
  56116. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  56117. /**
  56118. * Legacy support, changed quaternion to rotationQuaternion
  56119. */
  56120. get: function () {
  56121. return this.rotationQuaternion;
  56122. },
  56123. /**
  56124. * Legacy support, changed quaternion to rotationQuaternion
  56125. */
  56126. set: function (q) {
  56127. this.rotationQuaternion = q;
  56128. },
  56129. enumerable: true,
  56130. configurable: true
  56131. });
  56132. /**
  56133. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  56134. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  56135. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  56136. * @returns true if it intersects
  56137. */
  56138. SolidParticle.prototype.intersectsMesh = function (target) {
  56139. if (!this._boundingInfo || !target._boundingInfo) {
  56140. return false;
  56141. }
  56142. if (this._sps._bSphereOnly) {
  56143. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  56144. }
  56145. return this._boundingInfo.intersects(target._boundingInfo, false);
  56146. };
  56147. return SolidParticle;
  56148. }());
  56149. BABYLON.SolidParticle = SolidParticle;
  56150. /**
  56151. * Represents the shape of the model used by one particle of a solid particle system.
  56152. * SPS internal tool, don't use it manually.
  56153. */
  56154. var ModelShape = /** @class */ (function () {
  56155. /**
  56156. * 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.
  56157. * SPS internal tool, don't use it manually.
  56158. * @ignore
  56159. */
  56160. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  56161. /**
  56162. * length of the shape in the model indices array (internal use)
  56163. */
  56164. this._indicesLength = 0;
  56165. this.shapeID = id;
  56166. this._shape = shape;
  56167. this._indicesLength = indicesLength;
  56168. this._shapeUV = shapeUV;
  56169. this._positionFunction = posFunction;
  56170. this._vertexFunction = vtxFunction;
  56171. }
  56172. return ModelShape;
  56173. }());
  56174. BABYLON.ModelShape = ModelShape;
  56175. /**
  56176. * Represents a Depth Sorted Particle in the solid particle system.
  56177. */
  56178. var DepthSortedParticle = /** @class */ (function () {
  56179. function DepthSortedParticle() {
  56180. /**
  56181. * Index of the particle in the "indices" array
  56182. */
  56183. this.ind = 0;
  56184. /**
  56185. * Length of the particle shape in the "indices" array
  56186. */
  56187. this.indicesLength = 0;
  56188. /**
  56189. * Squared distance from the particle to the camera
  56190. */
  56191. this.sqDistance = 0.0;
  56192. }
  56193. return DepthSortedParticle;
  56194. }());
  56195. BABYLON.DepthSortedParticle = DepthSortedParticle;
  56196. })(BABYLON || (BABYLON = {}));
  56197. //# sourceMappingURL=babylon.solidParticle.js.map
  56198. "use strict";
  56199. var BABYLON;
  56200. (function (BABYLON) {
  56201. /**
  56202. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  56203. *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.
  56204. * The SPS is also a particle system. It provides some methods to manage the particles.
  56205. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  56206. *
  56207. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  56208. */
  56209. var SolidParticleSystem = /** @class */ (function () {
  56210. /**
  56211. * Creates a SPS (Solid Particle System) object.
  56212. * @param name (String) is the SPS name, this will be the underlying mesh name.
  56213. * @param scene (Scene) is the scene in which the SPS is added.
  56214. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  56215. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  56216. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  56217. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  56218. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  56219. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  56220. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  56221. */
  56222. function SolidParticleSystem(name, scene, options) {
  56223. /**
  56224. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  56225. * Example : var p = SPS.particles[i];
  56226. */
  56227. this.particles = new Array();
  56228. /**
  56229. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  56230. */
  56231. this.nbParticles = 0;
  56232. /**
  56233. * If the particles must ever face the camera (default false). Useful for planar particles.
  56234. */
  56235. this.billboard = false;
  56236. /**
  56237. * Recompute normals when adding a shape
  56238. */
  56239. this.recomputeNormals = true;
  56240. /**
  56241. * This a counter ofr your own usage. It's not set by any SPS functions.
  56242. */
  56243. this.counter = 0;
  56244. /**
  56245. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  56246. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  56247. */
  56248. this.vars = {};
  56249. /**
  56250. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  56251. */
  56252. this._bSphereOnly = false;
  56253. /**
  56254. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  56255. */
  56256. this._bSphereRadiusFactor = 1.0;
  56257. this._positions = new Array();
  56258. this._indices = new Array();
  56259. this._normals = new Array();
  56260. this._colors = new Array();
  56261. this._uvs = new Array();
  56262. this._index = 0; // indices index
  56263. this._updatable = true;
  56264. this._pickable = false;
  56265. this._isVisibilityBoxLocked = false;
  56266. this._alwaysVisible = false;
  56267. this._depthSort = false;
  56268. this._shapeCounter = 0;
  56269. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  56270. this._color = new BABYLON.Color4(0, 0, 0, 0);
  56271. this._computeParticleColor = true;
  56272. this._computeParticleTexture = true;
  56273. this._computeParticleRotation = true;
  56274. this._computeParticleVertex = false;
  56275. this._computeBoundingBox = false;
  56276. this._depthSortParticles = true;
  56277. this._cam_axisZ = BABYLON.Vector3.Zero();
  56278. this._cam_axisY = BABYLON.Vector3.Zero();
  56279. this._cam_axisX = BABYLON.Vector3.Zero();
  56280. this._axisZ = BABYLON.Axis.Z;
  56281. this._camDir = BABYLON.Vector3.Zero();
  56282. this._camInvertedPosition = BABYLON.Vector3.Zero();
  56283. this._rotMatrix = new BABYLON.Matrix();
  56284. this._invertMatrix = new BABYLON.Matrix();
  56285. this._rotated = BABYLON.Vector3.Zero();
  56286. this._quaternion = new BABYLON.Quaternion();
  56287. this._vertex = BABYLON.Vector3.Zero();
  56288. this._normal = BABYLON.Vector3.Zero();
  56289. this._yaw = 0.0;
  56290. this._pitch = 0.0;
  56291. this._roll = 0.0;
  56292. this._halfroll = 0.0;
  56293. this._halfpitch = 0.0;
  56294. this._halfyaw = 0.0;
  56295. this._sinRoll = 0.0;
  56296. this._cosRoll = 0.0;
  56297. this._sinPitch = 0.0;
  56298. this._cosPitch = 0.0;
  56299. this._sinYaw = 0.0;
  56300. this._cosYaw = 0.0;
  56301. this._mustUnrotateFixedNormals = false;
  56302. this._minimum = BABYLON.Vector3.Zero();
  56303. this._maximum = BABYLON.Vector3.Zero();
  56304. this._minBbox = BABYLON.Vector3.Zero();
  56305. this._maxBbox = BABYLON.Vector3.Zero();
  56306. this._particlesIntersect = false;
  56307. this._depthSortFunction = function (p1, p2) {
  56308. return (p2.sqDistance - p1.sqDistance);
  56309. };
  56310. this._needs32Bits = false;
  56311. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  56312. this._scaledPivot = BABYLON.Vector3.Zero();
  56313. this._particleHasParent = false;
  56314. this.name = name;
  56315. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56316. this._camera = scene.activeCamera;
  56317. this._pickable = options ? options.isPickable : false;
  56318. this._depthSort = options ? options.enableDepthSort : false;
  56319. this._particlesIntersect = options ? options.particleIntersection : false;
  56320. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  56321. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  56322. if (options && options.updatable) {
  56323. this._updatable = options.updatable;
  56324. }
  56325. else {
  56326. this._updatable = true;
  56327. }
  56328. if (this._pickable) {
  56329. this.pickedParticles = [];
  56330. }
  56331. if (this._depthSort) {
  56332. this.depthSortedParticles = [];
  56333. }
  56334. }
  56335. /**
  56336. * Builds the SPS underlying mesh. Returns a standard Mesh.
  56337. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  56338. * @returns the created mesh
  56339. */
  56340. SolidParticleSystem.prototype.buildMesh = function () {
  56341. if (this.nbParticles === 0) {
  56342. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  56343. this.addShape(triangle, 1);
  56344. triangle.dispose();
  56345. }
  56346. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  56347. this._positions32 = new Float32Array(this._positions);
  56348. this._uvs32 = new Float32Array(this._uvs);
  56349. this._colors32 = new Float32Array(this._colors);
  56350. if (this.recomputeNormals) {
  56351. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  56352. }
  56353. this._normals32 = new Float32Array(this._normals);
  56354. this._fixedNormal32 = new Float32Array(this._normals);
  56355. if (this._mustUnrotateFixedNormals) {
  56356. this._unrotateFixedNormals();
  56357. }
  56358. var vertexData = new BABYLON.VertexData();
  56359. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  56360. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  56361. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  56362. if (this._uvs32) {
  56363. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  56364. ;
  56365. }
  56366. if (this._colors32) {
  56367. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  56368. }
  56369. var mesh = new BABYLON.Mesh(this.name, this._scene);
  56370. vertexData.applyToMesh(mesh, this._updatable);
  56371. this.mesh = mesh;
  56372. this.mesh.isPickable = this._pickable;
  56373. // free memory
  56374. if (!this._depthSort) {
  56375. this._indices = null;
  56376. }
  56377. this._positions = null;
  56378. this._normals = null;
  56379. this._uvs = null;
  56380. this._colors = null;
  56381. if (!this._updatable) {
  56382. this.particles.length = 0;
  56383. }
  56384. return mesh;
  56385. };
  56386. /**
  56387. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  56388. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  56389. * Thus the particles generated from `digest()` have their property `position` set yet.
  56390. * @param mesh ( Mesh ) is the mesh to be digested
  56391. * @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
  56392. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  56393. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  56394. * @returns the current SPS
  56395. */
  56396. SolidParticleSystem.prototype.digest = function (mesh, options) {
  56397. var size = (options && options.facetNb) || 1;
  56398. var number = (options && options.number) || 0;
  56399. var delta = (options && options.delta) || 0;
  56400. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56401. var meshInd = mesh.getIndices();
  56402. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  56403. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  56404. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  56405. var f = 0; // facet counter
  56406. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  56407. // compute size from number
  56408. if (number) {
  56409. number = (number > totalFacets) ? totalFacets : number;
  56410. size = Math.round(totalFacets / number);
  56411. delta = 0;
  56412. }
  56413. else {
  56414. size = (size > totalFacets) ? totalFacets : size;
  56415. }
  56416. var facetPos = []; // submesh positions
  56417. var facetInd = []; // submesh indices
  56418. var facetUV = []; // submesh UV
  56419. var facetCol = []; // submesh colors
  56420. var barycenter = BABYLON.Vector3.Zero();
  56421. var sizeO = size;
  56422. while (f < totalFacets) {
  56423. size = sizeO + Math.floor((1 + delta) * Math.random());
  56424. if (f > totalFacets - size) {
  56425. size = totalFacets - f;
  56426. }
  56427. // reset temp arrays
  56428. facetPos.length = 0;
  56429. facetInd.length = 0;
  56430. facetUV.length = 0;
  56431. facetCol.length = 0;
  56432. // iterate over "size" facets
  56433. var fi = 0;
  56434. for (var j = f * 3; j < (f + size) * 3; j++) {
  56435. facetInd.push(fi);
  56436. var i = meshInd[j];
  56437. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  56438. if (meshUV) {
  56439. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  56440. }
  56441. if (meshCol) {
  56442. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  56443. }
  56444. fi++;
  56445. }
  56446. // create a model shape for each single particle
  56447. var idx = this.nbParticles;
  56448. var shape = this._posToShape(facetPos);
  56449. var shapeUV = this._uvsToShapeUV(facetUV);
  56450. // compute the barycenter of the shape
  56451. var v;
  56452. for (v = 0; v < shape.length; v++) {
  56453. barycenter.addInPlace(shape[v]);
  56454. }
  56455. barycenter.scaleInPlace(1 / shape.length);
  56456. // shift the shape from its barycenter to the origin
  56457. for (v = 0; v < shape.length; v++) {
  56458. shape[v].subtractInPlace(barycenter);
  56459. }
  56460. var bInfo;
  56461. if (this._particlesIntersect) {
  56462. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  56463. }
  56464. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  56465. // add the particle in the SPS
  56466. var currentPos = this._positions.length;
  56467. var currentInd = this._indices.length;
  56468. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  56469. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  56470. // initialize the particle position
  56471. this.particles[this.nbParticles].position.addInPlace(barycenter);
  56472. this._index += shape.length;
  56473. idx++;
  56474. this.nbParticles++;
  56475. this._shapeCounter++;
  56476. f += size;
  56477. }
  56478. return this;
  56479. };
  56480. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  56481. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  56482. var index = 0;
  56483. var idx = 0;
  56484. for (var p = 0; p < this.particles.length; p++) {
  56485. this._particle = this.particles[p];
  56486. this._shape = this._particle._model._shape;
  56487. if (this._particle.rotationQuaternion) {
  56488. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  56489. }
  56490. else {
  56491. this._yaw = this._particle.rotation.y;
  56492. this._pitch = this._particle.rotation.x;
  56493. this._roll = this._particle.rotation.z;
  56494. this._quaternionRotationYPR();
  56495. }
  56496. this._quaternionToRotationMatrix();
  56497. this._rotMatrix.invertToRef(this._invertMatrix);
  56498. for (var pt = 0; pt < this._shape.length; pt++) {
  56499. idx = index + pt * 3;
  56500. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  56501. this._fixedNormal32[idx] = this._normal.x;
  56502. this._fixedNormal32[idx + 1] = this._normal.y;
  56503. this._fixedNormal32[idx + 2] = this._normal.z;
  56504. }
  56505. index = idx + 3;
  56506. }
  56507. };
  56508. //reset copy
  56509. SolidParticleSystem.prototype._resetCopy = function () {
  56510. this._copy.position.x = 0;
  56511. this._copy.position.y = 0;
  56512. this._copy.position.z = 0;
  56513. this._copy.rotation.x = 0;
  56514. this._copy.rotation.y = 0;
  56515. this._copy.rotation.z = 0;
  56516. this._copy.rotationQuaternion = null;
  56517. this._copy.scaling.x = 1.0;
  56518. this._copy.scaling.y = 1.0;
  56519. this._copy.scaling.z = 1.0;
  56520. this._copy.uvs.x = 0;
  56521. this._copy.uvs.y = 0;
  56522. this._copy.uvs.z = 1.0;
  56523. this._copy.uvs.w = 1.0;
  56524. this._copy.color = null;
  56525. this._copy.translateFromPivot = false;
  56526. };
  56527. // _meshBuilder : inserts the shape model in the global SPS mesh
  56528. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  56529. var i;
  56530. var u = 0;
  56531. var c = 0;
  56532. var n = 0;
  56533. this._resetCopy();
  56534. if (options && options.positionFunction) {
  56535. options.positionFunction(this._copy, idx, idxInShape);
  56536. this._mustUnrotateFixedNormals = true;
  56537. }
  56538. if (this._copy.rotationQuaternion) {
  56539. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  56540. }
  56541. else {
  56542. this._yaw = this._copy.rotation.y;
  56543. this._pitch = this._copy.rotation.x;
  56544. this._roll = this._copy.rotation.z;
  56545. this._quaternionRotationYPR();
  56546. }
  56547. this._quaternionToRotationMatrix();
  56548. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  56549. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  56550. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  56551. if (this._copy.translateFromPivot) {
  56552. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  56553. }
  56554. else {
  56555. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  56556. }
  56557. for (i = 0; i < shape.length; i++) {
  56558. this._vertex.x = shape[i].x;
  56559. this._vertex.y = shape[i].y;
  56560. this._vertex.z = shape[i].z;
  56561. if (options && options.vertexFunction) {
  56562. options.vertexFunction(this._copy, this._vertex, i);
  56563. }
  56564. this._vertex.x *= this._copy.scaling.x;
  56565. this._vertex.y *= this._copy.scaling.y;
  56566. this._vertex.z *= this._copy.scaling.z;
  56567. this._vertex.x -= this._scaledPivot.x;
  56568. this._vertex.y -= this._scaledPivot.y;
  56569. this._vertex.z -= this._scaledPivot.z;
  56570. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  56571. this._rotated.addInPlace(this._pivotBackTranslation);
  56572. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  56573. if (meshUV) {
  56574. 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);
  56575. u += 2;
  56576. }
  56577. if (this._copy.color) {
  56578. this._color = this._copy.color;
  56579. }
  56580. else if (meshCol && meshCol[c] !== undefined) {
  56581. this._color.r = meshCol[c];
  56582. this._color.g = meshCol[c + 1];
  56583. this._color.b = meshCol[c + 2];
  56584. this._color.a = meshCol[c + 3];
  56585. }
  56586. else {
  56587. this._color.r = 1.0;
  56588. this._color.g = 1.0;
  56589. this._color.b = 1.0;
  56590. this._color.a = 1.0;
  56591. }
  56592. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  56593. c += 4;
  56594. if (!this.recomputeNormals && meshNor) {
  56595. this._normal.x = meshNor[n];
  56596. this._normal.y = meshNor[n + 1];
  56597. this._normal.z = meshNor[n + 2];
  56598. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  56599. normals.push(this._normal.x, this._normal.y, this._normal.z);
  56600. n += 3;
  56601. }
  56602. }
  56603. for (i = 0; i < meshInd.length; i++) {
  56604. var current_ind = p + meshInd[i];
  56605. indices.push(current_ind);
  56606. if (current_ind > 65535) {
  56607. this._needs32Bits = true;
  56608. }
  56609. }
  56610. if (this._pickable) {
  56611. var nbfaces = meshInd.length / 3;
  56612. for (i = 0; i < nbfaces; i++) {
  56613. this.pickedParticles.push({ idx: idx, faceId: i });
  56614. }
  56615. }
  56616. if (this._depthSort) {
  56617. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  56618. }
  56619. return this._copy;
  56620. };
  56621. // returns a shape array from positions array
  56622. SolidParticleSystem.prototype._posToShape = function (positions) {
  56623. var shape = [];
  56624. for (var i = 0; i < positions.length; i += 3) {
  56625. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  56626. }
  56627. return shape;
  56628. };
  56629. // returns a shapeUV array from a Vector4 uvs
  56630. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  56631. var shapeUV = [];
  56632. if (uvs) {
  56633. for (var i = 0; i < uvs.length; i++)
  56634. shapeUV.push(uvs[i]);
  56635. }
  56636. return shapeUV;
  56637. };
  56638. // adds a new particle object in the particles array
  56639. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  56640. if (bInfo === void 0) { bInfo = null; }
  56641. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  56642. this.particles.push(sp);
  56643. return sp;
  56644. };
  56645. /**
  56646. * Adds some particles to the SPS from the model shape. Returns the shape id.
  56647. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  56648. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  56649. * @param nb (positive integer) the number of particles to be created from this model
  56650. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  56651. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  56652. * @returns the number of shapes in the system
  56653. */
  56654. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  56655. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56656. var meshInd = mesh.getIndices();
  56657. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  56658. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  56659. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  56660. var bbInfo;
  56661. if (this._particlesIntersect) {
  56662. bbInfo = mesh.getBoundingInfo();
  56663. }
  56664. var shape = this._posToShape(meshPos);
  56665. var shapeUV = this._uvsToShapeUV(meshUV);
  56666. var posfunc = options ? options.positionFunction : null;
  56667. var vtxfunc = options ? options.vertexFunction : null;
  56668. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  56669. // particles
  56670. var sp;
  56671. var currentCopy;
  56672. var idx = this.nbParticles;
  56673. for (var i = 0; i < nb; i++) {
  56674. var currentPos = this._positions.length;
  56675. var currentInd = this._indices.length;
  56676. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  56677. if (this._updatable) {
  56678. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  56679. sp.position.copyFrom(currentCopy.position);
  56680. sp.rotation.copyFrom(currentCopy.rotation);
  56681. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  56682. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  56683. }
  56684. if (currentCopy.color && sp.color) {
  56685. sp.color.copyFrom(currentCopy.color);
  56686. }
  56687. sp.scaling.copyFrom(currentCopy.scaling);
  56688. sp.uvs.copyFrom(currentCopy.uvs);
  56689. }
  56690. this._index += shape.length;
  56691. idx++;
  56692. }
  56693. this.nbParticles += nb;
  56694. this._shapeCounter++;
  56695. return this._shapeCounter - 1;
  56696. };
  56697. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  56698. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  56699. this._resetCopy();
  56700. if (particle._model._positionFunction) {
  56701. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  56702. }
  56703. if (this._copy.rotationQuaternion) {
  56704. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  56705. }
  56706. else {
  56707. this._yaw = this._copy.rotation.y;
  56708. this._pitch = this._copy.rotation.x;
  56709. this._roll = this._copy.rotation.z;
  56710. this._quaternionRotationYPR();
  56711. }
  56712. this._quaternionToRotationMatrix();
  56713. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  56714. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  56715. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  56716. if (this._copy.translateFromPivot) {
  56717. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  56718. }
  56719. else {
  56720. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  56721. }
  56722. this._shape = particle._model._shape;
  56723. for (var pt = 0; pt < this._shape.length; pt++) {
  56724. this._vertex.x = this._shape[pt].x;
  56725. this._vertex.y = this._shape[pt].y;
  56726. this._vertex.z = this._shape[pt].z;
  56727. if (particle._model._vertexFunction) {
  56728. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  56729. }
  56730. this._vertex.x *= this._copy.scaling.x;
  56731. this._vertex.y *= this._copy.scaling.y;
  56732. this._vertex.z *= this._copy.scaling.z;
  56733. this._vertex.x -= this._scaledPivot.x;
  56734. this._vertex.y -= this._scaledPivot.y;
  56735. this._vertex.z -= this._scaledPivot.z;
  56736. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  56737. this._rotated.addInPlace(this._pivotBackTranslation);
  56738. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  56739. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  56740. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  56741. }
  56742. particle.position.x = 0.0;
  56743. particle.position.y = 0.0;
  56744. particle.position.z = 0.0;
  56745. particle.rotation.x = 0.0;
  56746. particle.rotation.y = 0.0;
  56747. particle.rotation.z = 0.0;
  56748. particle.rotationQuaternion = null;
  56749. particle.scaling.x = 1.0;
  56750. particle.scaling.y = 1.0;
  56751. particle.scaling.z = 1.0;
  56752. particle.uvs.x = 0.0;
  56753. particle.uvs.y = 0.0;
  56754. particle.uvs.z = 1.0;
  56755. particle.uvs.w = 1.0;
  56756. particle.pivot.x = 0.0;
  56757. particle.pivot.y = 0.0;
  56758. particle.pivot.z = 0.0;
  56759. particle.translateFromPivot = false;
  56760. particle.parentId = null;
  56761. };
  56762. /**
  56763. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  56764. * @returns the SPS.
  56765. */
  56766. SolidParticleSystem.prototype.rebuildMesh = function () {
  56767. for (var p = 0; p < this.particles.length; p++) {
  56768. this._rebuildParticle(this.particles[p]);
  56769. }
  56770. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  56771. return this;
  56772. };
  56773. /**
  56774. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  56775. * This method calls `updateParticle()` for each particle of the SPS.
  56776. * For an animated SPS, it is usually called within the render loop.
  56777. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  56778. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  56779. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  56780. * @returns the SPS.
  56781. */
  56782. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  56783. if (start === void 0) { start = 0; }
  56784. if (end === void 0) { end = this.nbParticles - 1; }
  56785. if (update === void 0) { update = true; }
  56786. if (!this._updatable) {
  56787. return this;
  56788. }
  56789. // custom beforeUpdate
  56790. this.beforeUpdateParticles(start, end, update);
  56791. this._cam_axisX.x = 1.0;
  56792. this._cam_axisX.y = 0.0;
  56793. this._cam_axisX.z = 0.0;
  56794. this._cam_axisY.x = 0.0;
  56795. this._cam_axisY.y = 1.0;
  56796. this._cam_axisY.z = 0.0;
  56797. this._cam_axisZ.x = 0.0;
  56798. this._cam_axisZ.y = 0.0;
  56799. this._cam_axisZ.z = 1.0;
  56800. // cases when the World Matrix is to be computed first
  56801. if (this.billboard || this._depthSort) {
  56802. this.mesh.computeWorldMatrix(true);
  56803. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  56804. }
  56805. // if the particles will always face the camera
  56806. if (this.billboard) {
  56807. // compute the camera position and un-rotate it by the current mesh rotation
  56808. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  56809. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  56810. this._cam_axisZ.normalize();
  56811. // same for camera up vector extracted from the cam view matrix
  56812. var view = this._camera.getViewMatrix(true);
  56813. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  56814. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  56815. this._cam_axisY.normalize();
  56816. this._cam_axisX.normalize();
  56817. }
  56818. // if depthSort, compute the camera global position in the mesh local system
  56819. if (this._depthSort) {
  56820. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  56821. }
  56822. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  56823. var idx = 0; // current position index in the global array positions32
  56824. var index = 0; // position start index in the global array positions32 of the current particle
  56825. var colidx = 0; // current color index in the global array colors32
  56826. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  56827. var uvidx = 0; // current uv index in the global array uvs32
  56828. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  56829. var pt = 0; // current index in the particle model shape
  56830. if (this.mesh.isFacetDataEnabled) {
  56831. this._computeBoundingBox = true;
  56832. }
  56833. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  56834. if (this._computeBoundingBox) {
  56835. if (start == 0 && end == this.nbParticles - 1) {
  56836. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  56837. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  56838. }
  56839. else {
  56840. if (this.mesh._boundingInfo) {
  56841. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  56842. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  56843. }
  56844. }
  56845. }
  56846. // particle loop
  56847. index = this.particles[start]._pos;
  56848. var vpos = (index / 3) | 0;
  56849. colorIndex = vpos * 4;
  56850. uvIndex = vpos * 2;
  56851. for (var p = start; p <= end; p++) {
  56852. this._particle = this.particles[p];
  56853. this._shape = this._particle._model._shape;
  56854. this._shapeUV = this._particle._model._shapeUV;
  56855. // call to custom user function to update the particle properties
  56856. this.updateParticle(this._particle);
  56857. // camera-particle distance for depth sorting
  56858. if (this._depthSort && this._depthSortParticles) {
  56859. var dsp = this.depthSortedParticles[p];
  56860. dsp.ind = this._particle._ind;
  56861. dsp.indicesLength = this._particle._model._indicesLength;
  56862. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  56863. }
  56864. // skip the computations for inactive or already invisible particles
  56865. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  56866. // increment indexes for the next particle
  56867. pt = this._shape.length;
  56868. index += pt * 3;
  56869. colorIndex += pt * 4;
  56870. uvIndex += pt * 2;
  56871. continue;
  56872. }
  56873. if (this._particle.isVisible) {
  56874. this._particle._stillInvisible = false; // un-mark permanent invisibility
  56875. this._particleHasParent = (this._particle.parentId !== null);
  56876. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  56877. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  56878. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  56879. // particle rotation matrix
  56880. if (this.billboard) {
  56881. this._particle.rotation.x = 0.0;
  56882. this._particle.rotation.y = 0.0;
  56883. }
  56884. if (this._computeParticleRotation || this.billboard) {
  56885. if (this._particle.rotationQuaternion) {
  56886. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  56887. }
  56888. else {
  56889. this._yaw = this._particle.rotation.y;
  56890. this._pitch = this._particle.rotation.x;
  56891. this._roll = this._particle.rotation.z;
  56892. this._quaternionRotationYPR();
  56893. }
  56894. this._quaternionToRotationMatrix();
  56895. }
  56896. if (this._particleHasParent) {
  56897. this._parent = this.particles[this._particle.parentId];
  56898. 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];
  56899. 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];
  56900. 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];
  56901. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  56902. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  56903. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  56904. if (this._computeParticleRotation || this.billboard) {
  56905. 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];
  56906. 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];
  56907. 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];
  56908. 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];
  56909. 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];
  56910. 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];
  56911. 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];
  56912. 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];
  56913. 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];
  56914. }
  56915. }
  56916. else {
  56917. this._particle._globalPosition.x = this._particle.position.x;
  56918. this._particle._globalPosition.y = this._particle.position.y;
  56919. this._particle._globalPosition.z = this._particle.position.z;
  56920. if (this._computeParticleRotation || this.billboard) {
  56921. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  56922. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  56923. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  56924. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  56925. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  56926. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  56927. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  56928. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  56929. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  56930. }
  56931. }
  56932. if (this._particle.translateFromPivot) {
  56933. this._pivotBackTranslation.x = 0.0;
  56934. this._pivotBackTranslation.y = 0.0;
  56935. this._pivotBackTranslation.z = 0.0;
  56936. }
  56937. else {
  56938. this._pivotBackTranslation.x = this._scaledPivot.x;
  56939. this._pivotBackTranslation.y = this._scaledPivot.y;
  56940. this._pivotBackTranslation.z = this._scaledPivot.z;
  56941. }
  56942. // particle vertex loop
  56943. for (pt = 0; pt < this._shape.length; pt++) {
  56944. idx = index + pt * 3;
  56945. colidx = colorIndex + pt * 4;
  56946. uvidx = uvIndex + pt * 2;
  56947. this._vertex.x = this._shape[pt].x;
  56948. this._vertex.y = this._shape[pt].y;
  56949. this._vertex.z = this._shape[pt].z;
  56950. if (this._computeParticleVertex) {
  56951. this.updateParticleVertex(this._particle, this._vertex, pt);
  56952. }
  56953. // positions
  56954. this._vertex.x *= this._particle.scaling.x;
  56955. this._vertex.y *= this._particle.scaling.y;
  56956. this._vertex.z *= this._particle.scaling.z;
  56957. this._vertex.x -= this._scaledPivot.x;
  56958. this._vertex.y -= this._scaledPivot.y;
  56959. this._vertex.z -= this._scaledPivot.z;
  56960. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  56961. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  56962. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  56963. this._rotated.x += this._pivotBackTranslation.x;
  56964. this._rotated.y += this._pivotBackTranslation.y;
  56965. this._rotated.z += this._pivotBackTranslation.z;
  56966. 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;
  56967. 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;
  56968. 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;
  56969. if (this._computeBoundingBox) {
  56970. if (this._positions32[idx] < this._minimum.x) {
  56971. this._minimum.x = this._positions32[idx];
  56972. }
  56973. if (this._positions32[idx] > this._maximum.x) {
  56974. this._maximum.x = this._positions32[idx];
  56975. }
  56976. if (this._positions32[idx + 1] < this._minimum.y) {
  56977. this._minimum.y = this._positions32[idx + 1];
  56978. }
  56979. if (this._positions32[idx + 1] > this._maximum.y) {
  56980. this._maximum.y = this._positions32[idx + 1];
  56981. }
  56982. if (this._positions32[idx + 2] < this._minimum.z) {
  56983. this._minimum.z = this._positions32[idx + 2];
  56984. }
  56985. if (this._positions32[idx + 2] > this._maximum.z) {
  56986. this._maximum.z = this._positions32[idx + 2];
  56987. }
  56988. }
  56989. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  56990. if (!this._computeParticleVertex) {
  56991. this._normal.x = this._fixedNormal32[idx];
  56992. this._normal.y = this._fixedNormal32[idx + 1];
  56993. this._normal.z = this._fixedNormal32[idx + 2];
  56994. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  56995. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  56996. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  56997. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  56998. 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;
  56999. 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;
  57000. }
  57001. if (this._computeParticleColor && this._particle.color) {
  57002. this._colors32[colidx] = this._particle.color.r;
  57003. this._colors32[colidx + 1] = this._particle.color.g;
  57004. this._colors32[colidx + 2] = this._particle.color.b;
  57005. this._colors32[colidx + 3] = this._particle.color.a;
  57006. }
  57007. if (this._computeParticleTexture) {
  57008. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  57009. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  57010. }
  57011. }
  57012. }
  57013. else {
  57014. this._particle._stillInvisible = true; // mark the particle as invisible
  57015. for (pt = 0; pt < this._shape.length; pt++) {
  57016. idx = index + pt * 3;
  57017. colidx = colorIndex + pt * 4;
  57018. uvidx = uvIndex + pt * 2;
  57019. this._positions32[idx] = 0.0;
  57020. this._positions32[idx + 1] = 0.0;
  57021. this._positions32[idx + 2] = 0.0;
  57022. this._normals32[idx] = 0.0;
  57023. this._normals32[idx + 1] = 0.0;
  57024. this._normals32[idx + 2] = 0.0;
  57025. if (this._computeParticleColor && this._particle.color) {
  57026. this._colors32[colidx] = this._particle.color.r;
  57027. this._colors32[colidx + 1] = this._particle.color.g;
  57028. this._colors32[colidx + 2] = this._particle.color.b;
  57029. this._colors32[colidx + 3] = this._particle.color.a;
  57030. }
  57031. if (this._computeParticleTexture) {
  57032. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  57033. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  57034. }
  57035. }
  57036. }
  57037. // if the particle intersections must be computed : update the bbInfo
  57038. if (this._particlesIntersect) {
  57039. var bInfo = this._particle._boundingInfo;
  57040. var bBox = bInfo.boundingBox;
  57041. var bSphere = bInfo.boundingSphere;
  57042. if (!this._bSphereOnly) {
  57043. // place, scale and rotate the particle bbox within the SPS local system, then update it
  57044. for (var b = 0; b < bBox.vectors.length; b++) {
  57045. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  57046. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  57047. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  57048. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  57049. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  57050. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  57051. 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;
  57052. 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;
  57053. 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;
  57054. }
  57055. bBox._update(this.mesh._worldMatrix);
  57056. }
  57057. // place and scale the particle bouding sphere in the SPS local system, then update it
  57058. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  57059. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  57060. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  57061. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  57062. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  57063. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  57064. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  57065. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  57066. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  57067. 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));
  57068. bSphere._update(this.mesh._worldMatrix);
  57069. }
  57070. // increment indexes for the next particle
  57071. index = idx + 3;
  57072. colorIndex = colidx + 4;
  57073. uvIndex = uvidx + 2;
  57074. }
  57075. // if the VBO must be updated
  57076. if (update) {
  57077. if (this._computeParticleColor) {
  57078. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  57079. }
  57080. if (this._computeParticleTexture) {
  57081. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  57082. }
  57083. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  57084. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  57085. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  57086. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  57087. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  57088. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  57089. for (var i = 0; i < this._normals32.length; i++) {
  57090. this._fixedNormal32[i] = this._normals32[i];
  57091. }
  57092. }
  57093. if (!this.mesh.areNormalsFrozen) {
  57094. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  57095. }
  57096. }
  57097. if (this._depthSort && this._depthSortParticles) {
  57098. this.depthSortedParticles.sort(this._depthSortFunction);
  57099. var dspl = this.depthSortedParticles.length;
  57100. var sorted = 0;
  57101. var lind = 0;
  57102. var sind = 0;
  57103. var sid = 0;
  57104. for (sorted = 0; sorted < dspl; sorted++) {
  57105. lind = this.depthSortedParticles[sorted].indicesLength;
  57106. sind = this.depthSortedParticles[sorted].ind;
  57107. for (var i = 0; i < lind; i++) {
  57108. this._indices32[sid] = this._indices[sind + i];
  57109. sid++;
  57110. }
  57111. }
  57112. this.mesh.updateIndices(this._indices32);
  57113. }
  57114. }
  57115. if (this._computeBoundingBox) {
  57116. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  57117. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  57118. }
  57119. this.afterUpdateParticles(start, end, update);
  57120. return this;
  57121. };
  57122. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  57123. this._halfroll = this._roll * 0.5;
  57124. this._halfpitch = this._pitch * 0.5;
  57125. this._halfyaw = this._yaw * 0.5;
  57126. this._sinRoll = Math.sin(this._halfroll);
  57127. this._cosRoll = Math.cos(this._halfroll);
  57128. this._sinPitch = Math.sin(this._halfpitch);
  57129. this._cosPitch = Math.cos(this._halfpitch);
  57130. this._sinYaw = Math.sin(this._halfyaw);
  57131. this._cosYaw = Math.cos(this._halfyaw);
  57132. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  57133. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  57134. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  57135. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  57136. };
  57137. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  57138. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  57139. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  57140. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  57141. this._rotMatrix.m[3] = 0;
  57142. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  57143. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  57144. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  57145. this._rotMatrix.m[7] = 0;
  57146. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  57147. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  57148. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  57149. this._rotMatrix.m[11] = 0;
  57150. this._rotMatrix.m[12] = 0;
  57151. this._rotMatrix.m[13] = 0;
  57152. this._rotMatrix.m[14] = 0;
  57153. this._rotMatrix.m[15] = 1.0;
  57154. };
  57155. /**
  57156. * Disposes the SPS.
  57157. */
  57158. SolidParticleSystem.prototype.dispose = function () {
  57159. this.mesh.dispose();
  57160. this.vars = null;
  57161. // drop references to internal big arrays for the GC
  57162. this._positions = null;
  57163. this._indices = null;
  57164. this._normals = null;
  57165. this._uvs = null;
  57166. this._colors = null;
  57167. this._indices32 = null;
  57168. this._positions32 = null;
  57169. this._normals32 = null;
  57170. this._fixedNormal32 = null;
  57171. this._uvs32 = null;
  57172. this._colors32 = null;
  57173. this.pickedParticles = null;
  57174. };
  57175. /**
  57176. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  57177. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57178. * @returns the SPS.
  57179. */
  57180. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  57181. if (!this._isVisibilityBoxLocked) {
  57182. this.mesh.refreshBoundingInfo();
  57183. }
  57184. return this;
  57185. };
  57186. /**
  57187. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  57188. * @param size the size (float) of the visibility box
  57189. * note : this doesn't lock the SPS mesh bounding box.
  57190. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57191. */
  57192. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  57193. var vis = size / 2;
  57194. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  57195. };
  57196. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  57197. /**
  57198. * Gets whether the SPS as always visible or not
  57199. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57200. */
  57201. get: function () {
  57202. return this._alwaysVisible;
  57203. },
  57204. /**
  57205. * Sets the SPS as always visible or not
  57206. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57207. */
  57208. set: function (val) {
  57209. this._alwaysVisible = val;
  57210. this.mesh.alwaysSelectAsActiveMesh = val;
  57211. },
  57212. enumerable: true,
  57213. configurable: true
  57214. });
  57215. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  57216. /**
  57217. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  57218. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57219. */
  57220. get: function () {
  57221. return this._isVisibilityBoxLocked;
  57222. },
  57223. /**
  57224. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  57225. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57226. */
  57227. set: function (val) {
  57228. this._isVisibilityBoxLocked = val;
  57229. var boundingInfo = this.mesh.getBoundingInfo();
  57230. boundingInfo.isLocked = val;
  57231. },
  57232. enumerable: true,
  57233. configurable: true
  57234. });
  57235. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  57236. /**
  57237. * Gets if `setParticles()` computes the particle rotations or not.
  57238. * Default value : true. The SPS is faster when it's set to false.
  57239. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  57240. */
  57241. get: function () {
  57242. return this._computeParticleRotation;
  57243. },
  57244. /**
  57245. * Tells to `setParticles()` to compute the particle rotations or not.
  57246. * Default value : true. The SPS is faster when it's set to false.
  57247. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  57248. */
  57249. set: function (val) {
  57250. this._computeParticleRotation = val;
  57251. },
  57252. enumerable: true,
  57253. configurable: true
  57254. });
  57255. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  57256. /**
  57257. * Gets if `setParticles()` computes the particle colors or not.
  57258. * Default value : true. The SPS is faster when it's set to false.
  57259. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  57260. */
  57261. get: function () {
  57262. return this._computeParticleColor;
  57263. },
  57264. /**
  57265. * Tells to `setParticles()` to compute the particle colors or not.
  57266. * Default value : true. The SPS is faster when it's set to false.
  57267. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  57268. */
  57269. set: function (val) {
  57270. this._computeParticleColor = val;
  57271. },
  57272. enumerable: true,
  57273. configurable: true
  57274. });
  57275. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  57276. /**
  57277. * Gets if `setParticles()` computes the particle textures or not.
  57278. * Default value : true. The SPS is faster when it's set to false.
  57279. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  57280. */
  57281. get: function () {
  57282. return this._computeParticleTexture;
  57283. },
  57284. set: function (val) {
  57285. this._computeParticleTexture = val;
  57286. },
  57287. enumerable: true,
  57288. configurable: true
  57289. });
  57290. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  57291. /**
  57292. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  57293. * Default value : false. The SPS is faster when it's set to false.
  57294. * Note : the particle custom vertex positions aren't stored values.
  57295. */
  57296. get: function () {
  57297. return this._computeParticleVertex;
  57298. },
  57299. /**
  57300. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  57301. * Default value : false. The SPS is faster when it's set to false.
  57302. * Note : the particle custom vertex positions aren't stored values.
  57303. */
  57304. set: function (val) {
  57305. this._computeParticleVertex = val;
  57306. },
  57307. enumerable: true,
  57308. configurable: true
  57309. });
  57310. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  57311. /**
  57312. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  57313. */
  57314. get: function () {
  57315. return this._computeBoundingBox;
  57316. },
  57317. /**
  57318. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  57319. */
  57320. set: function (val) {
  57321. this._computeBoundingBox = val;
  57322. },
  57323. enumerable: true,
  57324. configurable: true
  57325. });
  57326. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  57327. /**
  57328. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  57329. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  57330. * Default : `true`
  57331. */
  57332. get: function () {
  57333. return this._depthSortParticles;
  57334. },
  57335. /**
  57336. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  57337. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  57338. * Default : `true`
  57339. */
  57340. set: function (val) {
  57341. this._depthSortParticles = val;
  57342. },
  57343. enumerable: true,
  57344. configurable: true
  57345. });
  57346. // =======================================================================
  57347. // Particle behavior logic
  57348. // these following methods may be overwritten by the user to fit his needs
  57349. /**
  57350. * This function does nothing. It may be overwritten to set all the particle first values.
  57351. * The SPS doesn't call this function, you may have to call it by your own.
  57352. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  57353. */
  57354. SolidParticleSystem.prototype.initParticles = function () {
  57355. };
  57356. /**
  57357. * This function does nothing. It may be overwritten to recycle a particle.
  57358. * The SPS doesn't call this function, you may have to call it by your own.
  57359. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  57360. * @param particle The particle to recycle
  57361. * @returns the recycled particle
  57362. */
  57363. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  57364. return particle;
  57365. };
  57366. /**
  57367. * Updates a particle : this function should be overwritten by the user.
  57368. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  57369. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  57370. * @example : just set a particle position or velocity and recycle conditions
  57371. * @param particle The particle to update
  57372. * @returns the updated particle
  57373. */
  57374. SolidParticleSystem.prototype.updateParticle = function (particle) {
  57375. return particle;
  57376. };
  57377. /**
  57378. * Updates a vertex of a particle : it can be overwritten by the user.
  57379. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  57380. * @param particle the current particle
  57381. * @param vertex the current index of the current particle
  57382. * @param pt the index of the current vertex in the particle shape
  57383. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  57384. * @example : just set a vertex particle position
  57385. * @returns the updated vertex
  57386. */
  57387. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  57388. return vertex;
  57389. };
  57390. /**
  57391. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  57392. * This does nothing and may be overwritten by the user.
  57393. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  57394. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  57395. * @param update the boolean update value actually passed to setParticles()
  57396. */
  57397. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  57398. };
  57399. /**
  57400. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  57401. * This will be passed three parameters.
  57402. * This does nothing and may be overwritten by the user.
  57403. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  57404. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  57405. * @param update the boolean update value actually passed to setParticles()
  57406. */
  57407. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  57408. };
  57409. return SolidParticleSystem;
  57410. }());
  57411. BABYLON.SolidParticleSystem = SolidParticleSystem;
  57412. })(BABYLON || (BABYLON = {}));
  57413. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  57414. "use strict";
  57415. var BABYLON;
  57416. (function (BABYLON) {
  57417. var ShaderMaterial = /** @class */ (function (_super) {
  57418. __extends(ShaderMaterial, _super);
  57419. function ShaderMaterial(name, scene, shaderPath, options) {
  57420. var _this = _super.call(this, name, scene) || this;
  57421. _this._textures = {};
  57422. _this._textureArrays = {};
  57423. _this._floats = {};
  57424. _this._ints = {};
  57425. _this._floatsArrays = {};
  57426. _this._colors3 = {};
  57427. _this._colors3Arrays = {};
  57428. _this._colors4 = {};
  57429. _this._vectors2 = {};
  57430. _this._vectors3 = {};
  57431. _this._vectors4 = {};
  57432. _this._matrices = {};
  57433. _this._matrices3x3 = {};
  57434. _this._matrices2x2 = {};
  57435. _this._vectors2Arrays = {};
  57436. _this._vectors3Arrays = {};
  57437. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  57438. _this._shaderPath = shaderPath;
  57439. options.needAlphaBlending = options.needAlphaBlending || false;
  57440. options.needAlphaTesting = options.needAlphaTesting || false;
  57441. options.attributes = options.attributes || ["position", "normal", "uv"];
  57442. options.uniforms = options.uniforms || ["worldViewProjection"];
  57443. options.uniformBuffers = options.uniformBuffers || [];
  57444. options.samplers = options.samplers || [];
  57445. options.defines = options.defines || [];
  57446. _this._options = options;
  57447. return _this;
  57448. }
  57449. ShaderMaterial.prototype.getClassName = function () {
  57450. return "ShaderMaterial";
  57451. };
  57452. ShaderMaterial.prototype.needAlphaBlending = function () {
  57453. return this._options.needAlphaBlending;
  57454. };
  57455. ShaderMaterial.prototype.needAlphaTesting = function () {
  57456. return this._options.needAlphaTesting;
  57457. };
  57458. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  57459. if (this._options.uniforms.indexOf(uniformName) === -1) {
  57460. this._options.uniforms.push(uniformName);
  57461. }
  57462. };
  57463. ShaderMaterial.prototype.setTexture = function (name, texture) {
  57464. if (this._options.samplers.indexOf(name) === -1) {
  57465. this._options.samplers.push(name);
  57466. }
  57467. this._textures[name] = texture;
  57468. return this;
  57469. };
  57470. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  57471. if (this._options.samplers.indexOf(name) === -1) {
  57472. this._options.samplers.push(name);
  57473. }
  57474. this._checkUniform(name);
  57475. this._textureArrays[name] = textures;
  57476. return this;
  57477. };
  57478. ShaderMaterial.prototype.setFloat = function (name, value) {
  57479. this._checkUniform(name);
  57480. this._floats[name] = value;
  57481. return this;
  57482. };
  57483. ShaderMaterial.prototype.setInt = function (name, value) {
  57484. this._checkUniform(name);
  57485. this._ints[name] = value;
  57486. return this;
  57487. };
  57488. ShaderMaterial.prototype.setFloats = function (name, value) {
  57489. this._checkUniform(name);
  57490. this._floatsArrays[name] = value;
  57491. return this;
  57492. };
  57493. ShaderMaterial.prototype.setColor3 = function (name, value) {
  57494. this._checkUniform(name);
  57495. this._colors3[name] = value;
  57496. return this;
  57497. };
  57498. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  57499. this._checkUniform(name);
  57500. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  57501. color.toArray(arr, arr.length);
  57502. return arr;
  57503. }, []);
  57504. return this;
  57505. };
  57506. ShaderMaterial.prototype.setColor4 = function (name, value) {
  57507. this._checkUniform(name);
  57508. this._colors4[name] = value;
  57509. return this;
  57510. };
  57511. ShaderMaterial.prototype.setVector2 = function (name, value) {
  57512. this._checkUniform(name);
  57513. this._vectors2[name] = value;
  57514. return this;
  57515. };
  57516. ShaderMaterial.prototype.setVector3 = function (name, value) {
  57517. this._checkUniform(name);
  57518. this._vectors3[name] = value;
  57519. return this;
  57520. };
  57521. ShaderMaterial.prototype.setVector4 = function (name, value) {
  57522. this._checkUniform(name);
  57523. this._vectors4[name] = value;
  57524. return this;
  57525. };
  57526. ShaderMaterial.prototype.setMatrix = function (name, value) {
  57527. this._checkUniform(name);
  57528. this._matrices[name] = value;
  57529. return this;
  57530. };
  57531. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  57532. this._checkUniform(name);
  57533. this._matrices3x3[name] = value;
  57534. return this;
  57535. };
  57536. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  57537. this._checkUniform(name);
  57538. this._matrices2x2[name] = value;
  57539. return this;
  57540. };
  57541. ShaderMaterial.prototype.setArray2 = function (name, value) {
  57542. this._checkUniform(name);
  57543. this._vectors2Arrays[name] = value;
  57544. return this;
  57545. };
  57546. ShaderMaterial.prototype.setArray3 = function (name, value) {
  57547. this._checkUniform(name);
  57548. this._vectors3Arrays[name] = value;
  57549. return this;
  57550. };
  57551. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  57552. if (!mesh) {
  57553. return true;
  57554. }
  57555. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  57556. return false;
  57557. }
  57558. return false;
  57559. };
  57560. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  57561. var scene = this.getScene();
  57562. var engine = scene.getEngine();
  57563. if (!this.checkReadyOnEveryCall) {
  57564. if (this._renderId === scene.getRenderId()) {
  57565. if (this._checkCache(scene, mesh, useInstances)) {
  57566. return true;
  57567. }
  57568. }
  57569. }
  57570. // Instances
  57571. var defines = [];
  57572. var attribs = [];
  57573. var fallbacks = new BABYLON.EffectFallbacks();
  57574. if (useInstances) {
  57575. defines.push("#define INSTANCES");
  57576. }
  57577. for (var index = 0; index < this._options.defines.length; index++) {
  57578. defines.push(this._options.defines[index]);
  57579. }
  57580. for (var index = 0; index < this._options.attributes.length; index++) {
  57581. attribs.push(this._options.attributes[index]);
  57582. }
  57583. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  57584. attribs.push(BABYLON.VertexBuffer.ColorKind);
  57585. defines.push("#define VERTEXCOLOR");
  57586. }
  57587. // Bones
  57588. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  57589. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  57590. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  57591. if (mesh.numBoneInfluencers > 4) {
  57592. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  57593. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  57594. }
  57595. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  57596. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  57597. fallbacks.addCPUSkinningFallback(0, mesh);
  57598. if (this._options.uniforms.indexOf("mBones") === -1) {
  57599. this._options.uniforms.push("mBones");
  57600. }
  57601. }
  57602. else {
  57603. defines.push("#define NUM_BONE_INFLUENCERS 0");
  57604. }
  57605. // Textures
  57606. for (var name in this._textures) {
  57607. if (!this._textures[name].isReady()) {
  57608. return false;
  57609. }
  57610. }
  57611. // Alpha test
  57612. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  57613. defines.push("#define ALPHATEST");
  57614. }
  57615. var previousEffect = this._effect;
  57616. var join = defines.join("\n");
  57617. this._effect = engine.createEffect(this._shaderPath, {
  57618. attributes: attribs,
  57619. uniformsNames: this._options.uniforms,
  57620. uniformBuffersNames: this._options.uniformBuffers,
  57621. samplers: this._options.samplers,
  57622. defines: join,
  57623. fallbacks: fallbacks,
  57624. onCompiled: this.onCompiled,
  57625. onError: this.onError
  57626. }, engine);
  57627. if (!this._effect.isReady()) {
  57628. return false;
  57629. }
  57630. if (previousEffect !== this._effect) {
  57631. scene.resetCachedMaterial();
  57632. }
  57633. this._renderId = scene.getRenderId();
  57634. return true;
  57635. };
  57636. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  57637. var scene = this.getScene();
  57638. if (!this._effect) {
  57639. return;
  57640. }
  57641. if (this._options.uniforms.indexOf("world") !== -1) {
  57642. this._effect.setMatrix("world", world);
  57643. }
  57644. if (this._options.uniforms.indexOf("worldView") !== -1) {
  57645. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  57646. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  57647. }
  57648. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  57649. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  57650. }
  57651. };
  57652. ShaderMaterial.prototype.bind = function (world, mesh) {
  57653. // Std values
  57654. this.bindOnlyWorldMatrix(world);
  57655. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  57656. if (this._options.uniforms.indexOf("view") !== -1) {
  57657. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  57658. }
  57659. if (this._options.uniforms.indexOf("projection") !== -1) {
  57660. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  57661. }
  57662. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  57663. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  57664. }
  57665. // Bones
  57666. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  57667. var name;
  57668. // Texture
  57669. for (name in this._textures) {
  57670. this._effect.setTexture(name, this._textures[name]);
  57671. }
  57672. // Texture arrays
  57673. for (name in this._textureArrays) {
  57674. this._effect.setTextureArray(name, this._textureArrays[name]);
  57675. }
  57676. // Int
  57677. for (name in this._ints) {
  57678. this._effect.setInt(name, this._ints[name]);
  57679. }
  57680. // Float
  57681. for (name in this._floats) {
  57682. this._effect.setFloat(name, this._floats[name]);
  57683. }
  57684. // Floats
  57685. for (name in this._floatsArrays) {
  57686. this._effect.setArray(name, this._floatsArrays[name]);
  57687. }
  57688. // Color3
  57689. for (name in this._colors3) {
  57690. this._effect.setColor3(name, this._colors3[name]);
  57691. }
  57692. for (name in this._colors3Arrays) {
  57693. this._effect.setArray3(name, this._colors3Arrays[name]);
  57694. }
  57695. // Color4
  57696. for (name in this._colors4) {
  57697. var color = this._colors4[name];
  57698. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  57699. }
  57700. // Vector2
  57701. for (name in this._vectors2) {
  57702. this._effect.setVector2(name, this._vectors2[name]);
  57703. }
  57704. // Vector3
  57705. for (name in this._vectors3) {
  57706. this._effect.setVector3(name, this._vectors3[name]);
  57707. }
  57708. // Vector4
  57709. for (name in this._vectors4) {
  57710. this._effect.setVector4(name, this._vectors4[name]);
  57711. }
  57712. // Matrix
  57713. for (name in this._matrices) {
  57714. this._effect.setMatrix(name, this._matrices[name]);
  57715. }
  57716. // Matrix 3x3
  57717. for (name in this._matrices3x3) {
  57718. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  57719. }
  57720. // Matrix 2x2
  57721. for (name in this._matrices2x2) {
  57722. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  57723. }
  57724. // Vector2Array
  57725. for (name in this._vectors2Arrays) {
  57726. this._effect.setArray2(name, this._vectors2Arrays[name]);
  57727. }
  57728. // Vector3Array
  57729. for (name in this._vectors3Arrays) {
  57730. this._effect.setArray3(name, this._vectors3Arrays[name]);
  57731. }
  57732. }
  57733. this._afterBind(mesh);
  57734. };
  57735. ShaderMaterial.prototype.getActiveTextures = function () {
  57736. var activeTextures = _super.prototype.getActiveTextures.call(this);
  57737. for (var name in this._textures) {
  57738. activeTextures.push(this._textures[name]);
  57739. }
  57740. for (var name in this._textureArrays) {
  57741. var array = this._textureArrays[name];
  57742. for (var index = 0; index < array.length; index++) {
  57743. activeTextures.push(array[index]);
  57744. }
  57745. }
  57746. return activeTextures;
  57747. };
  57748. ShaderMaterial.prototype.hasTexture = function (texture) {
  57749. if (_super.prototype.hasTexture.call(this, texture)) {
  57750. return true;
  57751. }
  57752. for (var name in this._textures) {
  57753. if (this._textures[name] === texture) {
  57754. return true;
  57755. }
  57756. }
  57757. for (var name in this._textureArrays) {
  57758. var array = this._textureArrays[name];
  57759. for (var index = 0; index < array.length; index++) {
  57760. if (array[index] === texture) {
  57761. return true;
  57762. }
  57763. }
  57764. }
  57765. return false;
  57766. };
  57767. ShaderMaterial.prototype.clone = function (name) {
  57768. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  57769. return newShaderMaterial;
  57770. };
  57771. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  57772. if (forceDisposeTextures) {
  57773. var name;
  57774. for (name in this._textures) {
  57775. this._textures[name].dispose();
  57776. }
  57777. for (name in this._textureArrays) {
  57778. var array = this._textureArrays[name];
  57779. for (var index = 0; index < array.length; index++) {
  57780. array[index].dispose();
  57781. }
  57782. }
  57783. }
  57784. this._textures = {};
  57785. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  57786. };
  57787. ShaderMaterial.prototype.serialize = function () {
  57788. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  57789. serializationObject.customType = "BABYLON.ShaderMaterial";
  57790. serializationObject.options = this._options;
  57791. serializationObject.shaderPath = this._shaderPath;
  57792. var name;
  57793. // Texture
  57794. serializationObject.textures = {};
  57795. for (name in this._textures) {
  57796. serializationObject.textures[name] = this._textures[name].serialize();
  57797. }
  57798. // Texture arrays
  57799. serializationObject.textureArrays = {};
  57800. for (name in this._textureArrays) {
  57801. serializationObject.textureArrays[name] = [];
  57802. var array = this._textureArrays[name];
  57803. for (var index = 0; index < array.length; index++) {
  57804. serializationObject.textureArrays[name].push(array[index].serialize());
  57805. }
  57806. }
  57807. // Float
  57808. serializationObject.floats = {};
  57809. for (name in this._floats) {
  57810. serializationObject.floats[name] = this._floats[name];
  57811. }
  57812. // Float s
  57813. serializationObject.FloatArrays = {};
  57814. for (name in this._floatsArrays) {
  57815. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  57816. }
  57817. // Color3
  57818. serializationObject.colors3 = {};
  57819. for (name in this._colors3) {
  57820. serializationObject.colors3[name] = this._colors3[name].asArray();
  57821. }
  57822. // Color3 array
  57823. serializationObject.colors3Arrays = {};
  57824. for (name in this._colors3Arrays) {
  57825. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  57826. }
  57827. // Color4
  57828. serializationObject.colors4 = {};
  57829. for (name in this._colors4) {
  57830. serializationObject.colors4[name] = this._colors4[name].asArray();
  57831. }
  57832. // Vector2
  57833. serializationObject.vectors2 = {};
  57834. for (name in this._vectors2) {
  57835. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  57836. }
  57837. // Vector3
  57838. serializationObject.vectors3 = {};
  57839. for (name in this._vectors3) {
  57840. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  57841. }
  57842. // Vector4
  57843. serializationObject.vectors4 = {};
  57844. for (name in this._vectors4) {
  57845. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  57846. }
  57847. // Matrix
  57848. serializationObject.matrices = {};
  57849. for (name in this._matrices) {
  57850. serializationObject.matrices[name] = this._matrices[name].asArray();
  57851. }
  57852. // Matrix 3x3
  57853. serializationObject.matrices3x3 = {};
  57854. for (name in this._matrices3x3) {
  57855. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  57856. }
  57857. // Matrix 2x2
  57858. serializationObject.matrices2x2 = {};
  57859. for (name in this._matrices2x2) {
  57860. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  57861. }
  57862. // Vector2Array
  57863. serializationObject.vectors2Arrays = {};
  57864. for (name in this._vectors2Arrays) {
  57865. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  57866. }
  57867. // Vector3Array
  57868. serializationObject.vectors3Arrays = {};
  57869. for (name in this._vectors3Arrays) {
  57870. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  57871. }
  57872. return serializationObject;
  57873. };
  57874. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  57875. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  57876. var name;
  57877. // Texture
  57878. for (name in source.textures) {
  57879. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  57880. }
  57881. // Texture arrays
  57882. for (name in source.textureArrays) {
  57883. var array = source.textureArrays[name];
  57884. var textureArray = new Array();
  57885. for (var index = 0; index < array.length; index++) {
  57886. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  57887. }
  57888. material.setTextureArray(name, textureArray);
  57889. }
  57890. // Float
  57891. for (name in source.floats) {
  57892. material.setFloat(name, source.floats[name]);
  57893. }
  57894. // Float s
  57895. for (name in source.floatsArrays) {
  57896. material.setFloats(name, source.floatsArrays[name]);
  57897. }
  57898. // Color3
  57899. for (name in source.colors3) {
  57900. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  57901. }
  57902. // Color3 arrays
  57903. for (name in source.colors3Arrays) {
  57904. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  57905. if (i % 3 === 0) {
  57906. arr.push([num]);
  57907. }
  57908. else {
  57909. arr[arr.length - 1].push(num);
  57910. }
  57911. return arr;
  57912. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  57913. material.setColor3Array(name, colors);
  57914. }
  57915. // Color4
  57916. for (name in source.colors4) {
  57917. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  57918. }
  57919. // Vector2
  57920. for (name in source.vectors2) {
  57921. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  57922. }
  57923. // Vector3
  57924. for (name in source.vectors3) {
  57925. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  57926. }
  57927. // Vector4
  57928. for (name in source.vectors4) {
  57929. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  57930. }
  57931. // Matrix
  57932. for (name in source.matrices) {
  57933. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  57934. }
  57935. // Matrix 3x3
  57936. for (name in source.matrices3x3) {
  57937. material.setMatrix3x3(name, source.matrices3x3[name]);
  57938. }
  57939. // Matrix 2x2
  57940. for (name in source.matrices2x2) {
  57941. material.setMatrix2x2(name, source.matrices2x2[name]);
  57942. }
  57943. // Vector2Array
  57944. for (name in source.vectors2Arrays) {
  57945. material.setArray2(name, source.vectors2Arrays[name]);
  57946. }
  57947. // Vector3Array
  57948. for (name in source.vectors3Arrays) {
  57949. material.setArray3(name, source.vectors3Arrays[name]);
  57950. }
  57951. return material;
  57952. };
  57953. return ShaderMaterial;
  57954. }(BABYLON.Material));
  57955. BABYLON.ShaderMaterial = ShaderMaterial;
  57956. })(BABYLON || (BABYLON = {}));
  57957. //# sourceMappingURL=babylon.shaderMaterial.js.map
  57958. "use strict";
  57959. var BABYLON;
  57960. (function (BABYLON) {
  57961. var GroundMesh = /** @class */ (function (_super) {
  57962. __extends(GroundMesh, _super);
  57963. function GroundMesh(name, scene) {
  57964. var _this = _super.call(this, name, scene) || this;
  57965. _this.generateOctree = false;
  57966. return _this;
  57967. }
  57968. GroundMesh.prototype.getClassName = function () {
  57969. return "GroundMesh";
  57970. };
  57971. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  57972. get: function () {
  57973. return Math.min(this._subdivisionsX, this._subdivisionsY);
  57974. },
  57975. enumerable: true,
  57976. configurable: true
  57977. });
  57978. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  57979. get: function () {
  57980. return this._subdivisionsX;
  57981. },
  57982. enumerable: true,
  57983. configurable: true
  57984. });
  57985. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  57986. get: function () {
  57987. return this._subdivisionsY;
  57988. },
  57989. enumerable: true,
  57990. configurable: true
  57991. });
  57992. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  57993. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  57994. this._subdivisionsX = chunksCount;
  57995. this._subdivisionsY = chunksCount;
  57996. this.subdivide(chunksCount);
  57997. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  57998. };
  57999. /**
  58000. * Returns a height (y) value in the Worl system :
  58001. * the ground altitude at the coordinates (x, z) expressed in the World system.
  58002. * Returns the ground y position if (x, z) are outside the ground surface.
  58003. */
  58004. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  58005. var world = this.getWorldMatrix();
  58006. var invMat = BABYLON.Tmp.Matrix[5];
  58007. world.invertToRef(invMat);
  58008. var tmpVect = BABYLON.Tmp.Vector3[8];
  58009. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  58010. x = tmpVect.x;
  58011. z = tmpVect.z;
  58012. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  58013. return this.position.y;
  58014. }
  58015. if (!this._heightQuads || this._heightQuads.length == 0) {
  58016. this._initHeightQuads();
  58017. this._computeHeightQuads();
  58018. }
  58019. var facet = this._getFacetAt(x, z);
  58020. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  58021. // return y in the World system
  58022. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  58023. return tmpVect.y;
  58024. };
  58025. /**
  58026. * Returns a normalized vector (Vector3) orthogonal to the ground
  58027. * at the ground coordinates (x, z) expressed in the World system.
  58028. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  58029. */
  58030. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  58031. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  58032. this.getNormalAtCoordinatesToRef(x, z, normal);
  58033. return normal;
  58034. };
  58035. /**
  58036. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  58037. * at the ground coordinates (x, z) expressed in the World system.
  58038. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  58039. * Returns the GroundMesh.
  58040. */
  58041. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  58042. var world = this.getWorldMatrix();
  58043. var tmpMat = BABYLON.Tmp.Matrix[5];
  58044. world.invertToRef(tmpMat);
  58045. var tmpVect = BABYLON.Tmp.Vector3[8];
  58046. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  58047. x = tmpVect.x;
  58048. z = tmpVect.z;
  58049. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  58050. return this;
  58051. }
  58052. if (!this._heightQuads || this._heightQuads.length == 0) {
  58053. this._initHeightQuads();
  58054. this._computeHeightQuads();
  58055. }
  58056. var facet = this._getFacetAt(x, z);
  58057. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  58058. return this;
  58059. };
  58060. /**
  58061. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  58062. * if the ground has been updated.
  58063. * This can be used in the render loop.
  58064. * Returns the GroundMesh.
  58065. */
  58066. GroundMesh.prototype.updateCoordinateHeights = function () {
  58067. if (!this._heightQuads || this._heightQuads.length == 0) {
  58068. this._initHeightQuads();
  58069. }
  58070. this._computeHeightQuads();
  58071. return this;
  58072. };
  58073. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  58074. GroundMesh.prototype._getFacetAt = function (x, z) {
  58075. // retrieve col and row from x, z coordinates in the ground local system
  58076. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  58077. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  58078. var quad = this._heightQuads[row * this._subdivisionsX + col];
  58079. var facet;
  58080. if (z < quad.slope.x * x + quad.slope.y) {
  58081. facet = quad.facet1;
  58082. }
  58083. else {
  58084. facet = quad.facet2;
  58085. }
  58086. return facet;
  58087. };
  58088. // Creates and populates the heightMap array with "facet" elements :
  58089. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  58090. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  58091. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  58092. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  58093. // Returns the GroundMesh.
  58094. GroundMesh.prototype._initHeightQuads = function () {
  58095. var subdivisionsX = this._subdivisionsX;
  58096. var subdivisionsY = this._subdivisionsY;
  58097. this._heightQuads = new Array();
  58098. for (var row = 0; row < subdivisionsY; row++) {
  58099. for (var col = 0; col < subdivisionsX; col++) {
  58100. 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) };
  58101. this._heightQuads[row * subdivisionsX + col] = quad;
  58102. }
  58103. }
  58104. return this;
  58105. };
  58106. // Compute each quad element values and update the the heightMap array :
  58107. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  58108. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  58109. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  58110. // Returns the GroundMesh.
  58111. GroundMesh.prototype._computeHeightQuads = function () {
  58112. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58113. if (!positions) {
  58114. return this;
  58115. }
  58116. var v1 = BABYLON.Tmp.Vector3[3];
  58117. var v2 = BABYLON.Tmp.Vector3[2];
  58118. var v3 = BABYLON.Tmp.Vector3[1];
  58119. var v4 = BABYLON.Tmp.Vector3[0];
  58120. var v1v2 = BABYLON.Tmp.Vector3[4];
  58121. var v1v3 = BABYLON.Tmp.Vector3[5];
  58122. var v1v4 = BABYLON.Tmp.Vector3[6];
  58123. var norm1 = BABYLON.Tmp.Vector3[7];
  58124. var norm2 = BABYLON.Tmp.Vector3[8];
  58125. var i = 0;
  58126. var j = 0;
  58127. var k = 0;
  58128. var cd = 0; // 2D slope coefficient : z = cd * x + h
  58129. var h = 0;
  58130. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  58131. var d2 = 0;
  58132. var subdivisionsX = this._subdivisionsX;
  58133. var subdivisionsY = this._subdivisionsY;
  58134. for (var row = 0; row < subdivisionsY; row++) {
  58135. for (var col = 0; col < subdivisionsX; col++) {
  58136. i = col * 3;
  58137. j = row * (subdivisionsX + 1) * 3;
  58138. k = (row + 1) * (subdivisionsX + 1) * 3;
  58139. v1.x = positions[j + i];
  58140. v1.y = positions[j + i + 1];
  58141. v1.z = positions[j + i + 2];
  58142. v2.x = positions[j + i + 3];
  58143. v2.y = positions[j + i + 4];
  58144. v2.z = positions[j + i + 5];
  58145. v3.x = positions[k + i];
  58146. v3.y = positions[k + i + 1];
  58147. v3.z = positions[k + i + 2];
  58148. v4.x = positions[k + i + 3];
  58149. v4.y = positions[k + i + 4];
  58150. v4.z = positions[k + i + 5];
  58151. // 2D slope V1V4
  58152. cd = (v4.z - v1.z) / (v4.x - v1.x);
  58153. h = v1.z - cd * v1.x; // v1 belongs to the slope
  58154. // facet equations :
  58155. // we compute each facet normal vector
  58156. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  58157. // we compute the value d by applying the equation to v1 which belongs to the plane
  58158. // then we store the facet equation in a Vector4
  58159. v2.subtractToRef(v1, v1v2);
  58160. v3.subtractToRef(v1, v1v3);
  58161. v4.subtractToRef(v1, v1v4);
  58162. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  58163. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  58164. norm1.normalize();
  58165. norm2.normalize();
  58166. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  58167. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  58168. var quad = this._heightQuads[row * subdivisionsX + col];
  58169. quad.slope.copyFromFloats(cd, h);
  58170. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  58171. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  58172. }
  58173. }
  58174. return this;
  58175. };
  58176. GroundMesh.prototype.serialize = function (serializationObject) {
  58177. _super.prototype.serialize.call(this, serializationObject);
  58178. serializationObject.subdivisionsX = this._subdivisionsX;
  58179. serializationObject.subdivisionsY = this._subdivisionsY;
  58180. serializationObject.minX = this._minX;
  58181. serializationObject.maxX = this._maxX;
  58182. serializationObject.minZ = this._minZ;
  58183. serializationObject.maxZ = this._maxZ;
  58184. serializationObject.width = this._width;
  58185. serializationObject.height = this._height;
  58186. };
  58187. GroundMesh.Parse = function (parsedMesh, scene) {
  58188. var result = new GroundMesh(parsedMesh.name, scene);
  58189. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  58190. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  58191. result._minX = parsedMesh.minX;
  58192. result._maxX = parsedMesh.maxX;
  58193. result._minZ = parsedMesh.minZ;
  58194. result._maxZ = parsedMesh.maxZ;
  58195. result._width = parsedMesh.width;
  58196. result._height = parsedMesh.height;
  58197. return result;
  58198. };
  58199. return GroundMesh;
  58200. }(BABYLON.Mesh));
  58201. BABYLON.GroundMesh = GroundMesh;
  58202. })(BABYLON || (BABYLON = {}));
  58203. //# sourceMappingURL=babylon.groundMesh.js.map
  58204. "use strict";
  58205. var BABYLON;
  58206. (function (BABYLON) {
  58207. /**
  58208. * Creates an instance based on a source mesh.
  58209. */
  58210. var InstancedMesh = /** @class */ (function (_super) {
  58211. __extends(InstancedMesh, _super);
  58212. function InstancedMesh(name, source) {
  58213. var _this = _super.call(this, name, source.getScene()) || this;
  58214. source.instances.push(_this);
  58215. _this._sourceMesh = source;
  58216. _this.position.copyFrom(source.position);
  58217. _this.rotation.copyFrom(source.rotation);
  58218. _this.scaling.copyFrom(source.scaling);
  58219. if (source.rotationQuaternion) {
  58220. _this.rotationQuaternion = source.rotationQuaternion.clone();
  58221. }
  58222. _this.infiniteDistance = source.infiniteDistance;
  58223. _this.setPivotMatrix(source.getPivotMatrix());
  58224. _this.refreshBoundingInfo();
  58225. _this._syncSubMeshes();
  58226. return _this;
  58227. }
  58228. /**
  58229. * Returns the string "InstancedMesh".
  58230. */
  58231. InstancedMesh.prototype.getClassName = function () {
  58232. return "InstancedMesh";
  58233. };
  58234. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  58235. // Methods
  58236. get: function () {
  58237. return this._sourceMesh.receiveShadows;
  58238. },
  58239. enumerable: true,
  58240. configurable: true
  58241. });
  58242. Object.defineProperty(InstancedMesh.prototype, "material", {
  58243. get: function () {
  58244. return this._sourceMesh.material;
  58245. },
  58246. enumerable: true,
  58247. configurable: true
  58248. });
  58249. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  58250. get: function () {
  58251. return this._sourceMesh.visibility;
  58252. },
  58253. enumerable: true,
  58254. configurable: true
  58255. });
  58256. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  58257. get: function () {
  58258. return this._sourceMesh.skeleton;
  58259. },
  58260. enumerable: true,
  58261. configurable: true
  58262. });
  58263. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  58264. get: function () {
  58265. return this._sourceMesh.renderingGroupId;
  58266. },
  58267. set: function (value) {
  58268. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  58269. return;
  58270. }
  58271. //no-op with warning
  58272. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  58273. },
  58274. enumerable: true,
  58275. configurable: true
  58276. });
  58277. /**
  58278. * Returns the total number of vertices (integer).
  58279. */
  58280. InstancedMesh.prototype.getTotalVertices = function () {
  58281. return this._sourceMesh.getTotalVertices();
  58282. };
  58283. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  58284. get: function () {
  58285. return this._sourceMesh;
  58286. },
  58287. enumerable: true,
  58288. configurable: true
  58289. });
  58290. /**
  58291. * Is this node ready to be used/rendered
  58292. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  58293. * @return {boolean} is it ready
  58294. */
  58295. InstancedMesh.prototype.isReady = function (completeCheck) {
  58296. if (completeCheck === void 0) { completeCheck = false; }
  58297. return this._sourceMesh.isReady(completeCheck, true);
  58298. };
  58299. /**
  58300. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  58301. */
  58302. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  58303. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  58304. };
  58305. /**
  58306. * Sets the vertex data of the mesh geometry for the requested `kind`.
  58307. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  58308. * The `data` are either a numeric array either a Float32Array.
  58309. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  58310. * 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).
  58311. * Note that a new underlying VertexBuffer object is created each call.
  58312. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  58313. *
  58314. * Possible `kind` values :
  58315. * - BABYLON.VertexBuffer.PositionKind
  58316. * - BABYLON.VertexBuffer.UVKind
  58317. * - BABYLON.VertexBuffer.UV2Kind
  58318. * - BABYLON.VertexBuffer.UV3Kind
  58319. * - BABYLON.VertexBuffer.UV4Kind
  58320. * - BABYLON.VertexBuffer.UV5Kind
  58321. * - BABYLON.VertexBuffer.UV6Kind
  58322. * - BABYLON.VertexBuffer.ColorKind
  58323. * - BABYLON.VertexBuffer.MatricesIndicesKind
  58324. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  58325. * - BABYLON.VertexBuffer.MatricesWeightsKind
  58326. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  58327. *
  58328. * Returns the Mesh.
  58329. */
  58330. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  58331. if (this.sourceMesh) {
  58332. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  58333. }
  58334. return this.sourceMesh;
  58335. };
  58336. /**
  58337. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  58338. * If the mesh has no geometry, it is simply returned as it is.
  58339. * The `data` are either a numeric array either a Float32Array.
  58340. * No new underlying VertexBuffer object is created.
  58341. * 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.
  58342. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  58343. *
  58344. * Possible `kind` values :
  58345. * - BABYLON.VertexBuffer.PositionKind
  58346. * - BABYLON.VertexBuffer.UVKind
  58347. * - BABYLON.VertexBuffer.UV2Kind
  58348. * - BABYLON.VertexBuffer.UV3Kind
  58349. * - BABYLON.VertexBuffer.UV4Kind
  58350. * - BABYLON.VertexBuffer.UV5Kind
  58351. * - BABYLON.VertexBuffer.UV6Kind
  58352. * - BABYLON.VertexBuffer.ColorKind
  58353. * - BABYLON.VertexBuffer.MatricesIndicesKind
  58354. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  58355. * - BABYLON.VertexBuffer.MatricesWeightsKind
  58356. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  58357. *
  58358. * Returns the Mesh.
  58359. */
  58360. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  58361. if (this.sourceMesh) {
  58362. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  58363. }
  58364. return this.sourceMesh;
  58365. };
  58366. /**
  58367. * Sets the mesh indices.
  58368. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  58369. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  58370. * This method creates a new index buffer each call.
  58371. * Returns the Mesh.
  58372. */
  58373. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  58374. if (totalVertices === void 0) { totalVertices = null; }
  58375. if (this.sourceMesh) {
  58376. this.sourceMesh.setIndices(indices, totalVertices);
  58377. }
  58378. return this.sourceMesh;
  58379. };
  58380. /**
  58381. * Boolean : True if the mesh owns the requested kind of data.
  58382. */
  58383. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  58384. return this._sourceMesh.isVerticesDataPresent(kind);
  58385. };
  58386. /**
  58387. * Returns an array of indices (IndicesArray).
  58388. */
  58389. InstancedMesh.prototype.getIndices = function () {
  58390. return this._sourceMesh.getIndices();
  58391. };
  58392. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  58393. get: function () {
  58394. return this._sourceMesh._positions;
  58395. },
  58396. enumerable: true,
  58397. configurable: true
  58398. });
  58399. /**
  58400. * Sets a new updated BoundingInfo to the mesh.
  58401. * Returns the mesh.
  58402. */
  58403. InstancedMesh.prototype.refreshBoundingInfo = function () {
  58404. var meshBB = this._sourceMesh.getBoundingInfo();
  58405. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  58406. this._updateBoundingInfo();
  58407. return this;
  58408. };
  58409. InstancedMesh.prototype._preActivate = function () {
  58410. if (this._currentLOD) {
  58411. this._currentLOD._preActivate();
  58412. }
  58413. return this;
  58414. };
  58415. InstancedMesh.prototype._activate = function (renderId) {
  58416. if (this._currentLOD) {
  58417. this._currentLOD._registerInstanceForRenderId(this, renderId);
  58418. }
  58419. return this;
  58420. };
  58421. /**
  58422. * Returns the current associated LOD AbstractMesh.
  58423. */
  58424. InstancedMesh.prototype.getLOD = function (camera) {
  58425. if (!camera) {
  58426. return this;
  58427. }
  58428. var boundingInfo = this.getBoundingInfo();
  58429. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  58430. if (this._currentLOD === this.sourceMesh) {
  58431. return this;
  58432. }
  58433. return this._currentLOD;
  58434. };
  58435. InstancedMesh.prototype._syncSubMeshes = function () {
  58436. this.releaseSubMeshes();
  58437. if (this._sourceMesh.subMeshes) {
  58438. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  58439. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  58440. }
  58441. }
  58442. return this;
  58443. };
  58444. InstancedMesh.prototype._generatePointsArray = function () {
  58445. return this._sourceMesh._generatePointsArray();
  58446. };
  58447. /**
  58448. * Creates a new InstancedMesh from the current mesh.
  58449. * - name (string) : the cloned mesh name
  58450. * - newParent (optional Node) : the optional Node to parent the clone to.
  58451. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  58452. *
  58453. * Returns the clone.
  58454. */
  58455. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  58456. var result = this._sourceMesh.createInstance(name);
  58457. // Deep copy
  58458. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  58459. // Bounding info
  58460. this.refreshBoundingInfo();
  58461. // Parent
  58462. if (newParent) {
  58463. result.parent = newParent;
  58464. }
  58465. if (!doNotCloneChildren) {
  58466. // Children
  58467. for (var index = 0; index < this.getScene().meshes.length; index++) {
  58468. var mesh = this.getScene().meshes[index];
  58469. if (mesh.parent === this) {
  58470. mesh.clone(mesh.name, result);
  58471. }
  58472. }
  58473. }
  58474. result.computeWorldMatrix(true);
  58475. return result;
  58476. };
  58477. /**
  58478. * Disposes the InstancedMesh.
  58479. * Returns nothing.
  58480. */
  58481. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  58482. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  58483. // Remove from mesh
  58484. var index = this._sourceMesh.instances.indexOf(this);
  58485. this._sourceMesh.instances.splice(index, 1);
  58486. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  58487. };
  58488. return InstancedMesh;
  58489. }(BABYLON.AbstractMesh));
  58490. BABYLON.InstancedMesh = InstancedMesh;
  58491. })(BABYLON || (BABYLON = {}));
  58492. //# sourceMappingURL=babylon.instancedMesh.js.map
  58493. "use strict";
  58494. var BABYLON;
  58495. (function (BABYLON) {
  58496. var LinesMesh = /** @class */ (function (_super) {
  58497. __extends(LinesMesh, _super);
  58498. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  58499. if (scene === void 0) { scene = null; }
  58500. if (parent === void 0) { parent = null; }
  58501. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  58502. _this.useVertexColor = useVertexColor;
  58503. _this.useVertexAlpha = useVertexAlpha;
  58504. _this.color = new BABYLON.Color3(1, 1, 1);
  58505. _this.alpha = 1;
  58506. if (source) {
  58507. _this.color = source.color.clone();
  58508. _this.alpha = source.alpha;
  58509. _this.useVertexColor = source.useVertexColor;
  58510. _this.useVertexAlpha = source.useVertexAlpha;
  58511. }
  58512. _this._intersectionThreshold = 0.1;
  58513. var defines = [];
  58514. var options = {
  58515. attributes: [BABYLON.VertexBuffer.PositionKind],
  58516. uniforms: ["world", "viewProjection"],
  58517. needAlphaBlending: true,
  58518. defines: defines
  58519. };
  58520. if (useVertexAlpha === false) {
  58521. options.needAlphaBlending = false;
  58522. }
  58523. if (!useVertexColor) {
  58524. options.uniforms.push("color");
  58525. }
  58526. else {
  58527. options.defines.push("#define VERTEXCOLOR");
  58528. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  58529. }
  58530. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  58531. return _this;
  58532. }
  58533. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  58534. /**
  58535. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  58536. * This margin is expressed in world space coordinates, so its value may vary.
  58537. * Default value is 0.1
  58538. * @returns the intersection Threshold value.
  58539. */
  58540. get: function () {
  58541. return this._intersectionThreshold;
  58542. },
  58543. /**
  58544. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  58545. * This margin is expressed in world space coordinates, so its value may vary.
  58546. * @param value the new threshold to apply
  58547. */
  58548. set: function (value) {
  58549. if (this._intersectionThreshold === value) {
  58550. return;
  58551. }
  58552. this._intersectionThreshold = value;
  58553. if (this.geometry) {
  58554. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  58555. }
  58556. },
  58557. enumerable: true,
  58558. configurable: true
  58559. });
  58560. /**
  58561. * Returns the string "LineMesh"
  58562. */
  58563. LinesMesh.prototype.getClassName = function () {
  58564. return "LinesMesh";
  58565. };
  58566. Object.defineProperty(LinesMesh.prototype, "material", {
  58567. get: function () {
  58568. return this._colorShader;
  58569. },
  58570. set: function (value) {
  58571. // Do nothing
  58572. },
  58573. enumerable: true,
  58574. configurable: true
  58575. });
  58576. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  58577. get: function () {
  58578. return false;
  58579. },
  58580. enumerable: true,
  58581. configurable: true
  58582. });
  58583. LinesMesh.prototype.createInstance = function (name) {
  58584. throw new Error("LinesMeshes do not support createInstance.");
  58585. };
  58586. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  58587. if (!this._geometry) {
  58588. return this;
  58589. }
  58590. // VBOs
  58591. this._geometry._bind(this._colorShader.getEffect());
  58592. // Color
  58593. if (!this.useVertexColor) {
  58594. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  58595. }
  58596. return this;
  58597. };
  58598. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  58599. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  58600. return this;
  58601. }
  58602. var engine = this.getScene().getEngine();
  58603. // Draw order
  58604. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  58605. return this;
  58606. };
  58607. LinesMesh.prototype.dispose = function (doNotRecurse) {
  58608. this._colorShader.dispose();
  58609. _super.prototype.dispose.call(this, doNotRecurse);
  58610. };
  58611. /**
  58612. * Returns a new LineMesh object cloned from the current one.
  58613. */
  58614. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  58615. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  58616. };
  58617. return LinesMesh;
  58618. }(BABYLON.Mesh));
  58619. BABYLON.LinesMesh = LinesMesh;
  58620. })(BABYLON || (BABYLON = {}));
  58621. //# sourceMappingURL=babylon.linesMesh.js.map
  58622. "use strict";
  58623. var BABYLON;
  58624. (function (BABYLON) {
  58625. var MeshBuilder = /** @class */ (function () {
  58626. function MeshBuilder() {
  58627. }
  58628. MeshBuilder.updateSideOrientation = function (orientation) {
  58629. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  58630. return BABYLON.Mesh.DOUBLESIDE;
  58631. }
  58632. if (orientation === undefined || orientation === null) {
  58633. return BABYLON.Mesh.FRONTSIDE;
  58634. }
  58635. return orientation;
  58636. };
  58637. /**
  58638. * Creates a box mesh.
  58639. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  58640. * The parameter `size` sets the size (float) of each box side (default 1).
  58641. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  58642. * 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).
  58643. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  58644. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  58645. * 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).
  58646. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  58647. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  58648. */
  58649. MeshBuilder.CreateBox = function (name, options, scene) {
  58650. if (scene === void 0) { scene = null; }
  58651. var box = new BABYLON.Mesh(name, scene);
  58652. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  58653. box._originalBuilderSideOrientation = options.sideOrientation;
  58654. var vertexData = BABYLON.VertexData.CreateBox(options);
  58655. vertexData.applyToMesh(box, options.updatable);
  58656. return box;
  58657. };
  58658. /**
  58659. * Creates a sphere mesh.
  58660. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  58661. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  58662. * 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`).
  58663. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  58664. * 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
  58665. * 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).
  58666. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  58667. * 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).
  58668. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  58669. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  58670. */
  58671. MeshBuilder.CreateSphere = function (name, options, scene) {
  58672. var sphere = new BABYLON.Mesh(name, scene);
  58673. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  58674. sphere._originalBuilderSideOrientation = options.sideOrientation;
  58675. var vertexData = BABYLON.VertexData.CreateSphere(options);
  58676. vertexData.applyToMesh(sphere, options.updatable);
  58677. return sphere;
  58678. };
  58679. /**
  58680. * Creates a plane polygonal mesh. By default, this is a disc.
  58681. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  58682. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  58683. * 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.
  58684. * 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
  58685. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  58686. * 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).
  58687. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  58688. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  58689. */
  58690. MeshBuilder.CreateDisc = function (name, options, scene) {
  58691. if (scene === void 0) { scene = null; }
  58692. var disc = new BABYLON.Mesh(name, scene);
  58693. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  58694. disc._originalBuilderSideOrientation = options.sideOrientation;
  58695. var vertexData = BABYLON.VertexData.CreateDisc(options);
  58696. vertexData.applyToMesh(disc, options.updatable);
  58697. return disc;
  58698. };
  58699. /**
  58700. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  58701. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  58702. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  58703. * 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`).
  58704. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  58705. * 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.
  58706. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  58707. * 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).
  58708. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  58709. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  58710. */
  58711. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  58712. var sphere = new BABYLON.Mesh(name, scene);
  58713. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  58714. sphere._originalBuilderSideOrientation = options.sideOrientation;
  58715. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  58716. vertexData.applyToMesh(sphere, options.updatable);
  58717. return sphere;
  58718. };
  58719. ;
  58720. /**
  58721. * Creates a ribbon mesh.
  58722. * 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.
  58723. *
  58724. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  58725. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  58726. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  58727. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  58728. * 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.
  58729. * 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.
  58730. * 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
  58731. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  58732. * 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).
  58733. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  58734. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  58735. * 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.
  58736. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  58737. * 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
  58738. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  58739. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  58740. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  58741. */
  58742. MeshBuilder.CreateRibbon = function (name, options, scene) {
  58743. if (scene === void 0) { scene = null; }
  58744. var pathArray = options.pathArray;
  58745. var closeArray = options.closeArray;
  58746. var closePath = options.closePath;
  58747. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  58748. var instance = options.instance;
  58749. var updatable = options.updatable;
  58750. if (instance) {
  58751. // positionFunction : ribbon case
  58752. // only pathArray and sideOrientation parameters are taken into account for positions update
  58753. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  58754. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  58755. var positionFunction = function (positions) {
  58756. var minlg = pathArray[0].length;
  58757. var i = 0;
  58758. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  58759. for (var si = 1; si <= ns; si++) {
  58760. for (var p = 0; p < pathArray.length; p++) {
  58761. var path = pathArray[p];
  58762. var l = path.length;
  58763. minlg = (minlg < l) ? minlg : l;
  58764. var j = 0;
  58765. while (j < minlg) {
  58766. positions[i] = path[j].x;
  58767. positions[i + 1] = path[j].y;
  58768. positions[i + 2] = path[j].z;
  58769. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  58770. BABYLON.Tmp.Vector3[0].x = path[j].x;
  58771. }
  58772. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  58773. BABYLON.Tmp.Vector3[1].x = path[j].x;
  58774. }
  58775. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  58776. BABYLON.Tmp.Vector3[0].y = path[j].y;
  58777. }
  58778. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  58779. BABYLON.Tmp.Vector3[1].y = path[j].y;
  58780. }
  58781. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  58782. BABYLON.Tmp.Vector3[0].z = path[j].z;
  58783. }
  58784. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  58785. BABYLON.Tmp.Vector3[1].z = path[j].z;
  58786. }
  58787. j++;
  58788. i += 3;
  58789. }
  58790. if (instance._closePath) {
  58791. positions[i] = path[0].x;
  58792. positions[i + 1] = path[0].y;
  58793. positions[i + 2] = path[0].z;
  58794. i += 3;
  58795. }
  58796. }
  58797. }
  58798. };
  58799. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58800. positionFunction(positions);
  58801. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  58802. instance._boundingInfo.update(instance._worldMatrix);
  58803. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  58804. if (options.colors) {
  58805. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58806. for (var c = 0; c < options.colors.length; c++) {
  58807. colors[c * 4] = options.colors[c].r;
  58808. colors[c * 4 + 1] = options.colors[c].g;
  58809. colors[c * 4 + 2] = options.colors[c].b;
  58810. colors[c * 4 + 3] = options.colors[c].a;
  58811. }
  58812. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  58813. }
  58814. if (options.uvs) {
  58815. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58816. for (var i = 0; i < options.uvs.length; i++) {
  58817. uvs[i * 2] = options.uvs[i].x;
  58818. uvs[i * 2 + 1] = options.uvs[i].y;
  58819. }
  58820. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  58821. }
  58822. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  58823. var indices = instance.getIndices();
  58824. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58825. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  58826. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  58827. if (instance._closePath) {
  58828. var indexFirst = 0;
  58829. var indexLast = 0;
  58830. for (var p = 0; p < pathArray.length; p++) {
  58831. indexFirst = instance._idx[p] * 3;
  58832. if (p + 1 < pathArray.length) {
  58833. indexLast = (instance._idx[p + 1] - 1) * 3;
  58834. }
  58835. else {
  58836. indexLast = normals.length - 3;
  58837. }
  58838. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  58839. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  58840. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  58841. normals[indexLast] = normals[indexFirst];
  58842. normals[indexLast + 1] = normals[indexFirst + 1];
  58843. normals[indexLast + 2] = normals[indexFirst + 2];
  58844. }
  58845. }
  58846. if (!(instance.areNormalsFrozen)) {
  58847. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  58848. }
  58849. }
  58850. return instance;
  58851. }
  58852. else {
  58853. var ribbon = new BABYLON.Mesh(name, scene);
  58854. ribbon._originalBuilderSideOrientation = sideOrientation;
  58855. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  58856. if (closePath) {
  58857. ribbon._idx = vertexData._idx;
  58858. }
  58859. ribbon._closePath = closePath;
  58860. ribbon._closeArray = closeArray;
  58861. vertexData.applyToMesh(ribbon, updatable);
  58862. return ribbon;
  58863. }
  58864. };
  58865. /**
  58866. * Creates a cylinder or a cone mesh.
  58867. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  58868. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  58869. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  58870. * 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.
  58871. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  58872. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  58873. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  58874. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  58875. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  58876. * 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).
  58877. * 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
  58878. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  58879. * 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
  58880. * 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.
  58881. * If `enclose` is false, a ring surface is one element.
  58882. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  58883. * 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
  58884. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  58885. * 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).
  58886. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  58887. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  58888. */
  58889. MeshBuilder.CreateCylinder = function (name, options, scene) {
  58890. var cylinder = new BABYLON.Mesh(name, scene);
  58891. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  58892. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  58893. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  58894. vertexData.applyToMesh(cylinder, options.updatable);
  58895. return cylinder;
  58896. };
  58897. /**
  58898. * Creates a torus mesh.
  58899. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  58900. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  58901. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  58902. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  58903. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  58904. * 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).
  58905. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  58906. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  58907. */
  58908. MeshBuilder.CreateTorus = function (name, options, scene) {
  58909. var torus = new BABYLON.Mesh(name, scene);
  58910. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  58911. torus._originalBuilderSideOrientation = options.sideOrientation;
  58912. var vertexData = BABYLON.VertexData.CreateTorus(options);
  58913. vertexData.applyToMesh(torus, options.updatable);
  58914. return torus;
  58915. };
  58916. /**
  58917. * Creates a torus knot mesh.
  58918. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  58919. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  58920. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  58921. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  58922. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  58923. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  58924. * 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).
  58925. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  58926. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  58927. */
  58928. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  58929. var torusKnot = new BABYLON.Mesh(name, scene);
  58930. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  58931. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  58932. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  58933. vertexData.applyToMesh(torusKnot, options.updatable);
  58934. return torusKnot;
  58935. };
  58936. /**
  58937. * Creates a line system mesh.
  58938. * A line system is a pool of many lines gathered in a single mesh.
  58939. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  58940. * 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.
  58941. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  58942. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  58943. * 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
  58944. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  58945. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  58946. * 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
  58947. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  58948. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  58949. */
  58950. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  58951. var instance = options.instance;
  58952. var lines = options.lines;
  58953. var colors = options.colors;
  58954. if (instance) {
  58955. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58956. var vertexColor;
  58957. var lineColors;
  58958. if (colors) {
  58959. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58960. }
  58961. var i = 0;
  58962. var c = 0;
  58963. for (var l = 0; l < lines.length; l++) {
  58964. var points = lines[l];
  58965. for (var p = 0; p < points.length; p++) {
  58966. positions[i] = points[p].x;
  58967. positions[i + 1] = points[p].y;
  58968. positions[i + 2] = points[p].z;
  58969. if (colors && vertexColor) {
  58970. lineColors = colors[l];
  58971. vertexColor[c] = lineColors[p].r;
  58972. vertexColor[c + 1] = lineColors[p].g;
  58973. vertexColor[c + 2] = lineColors[p].b;
  58974. vertexColor[c + 3] = lineColors[p].a;
  58975. c += 4;
  58976. }
  58977. i += 3;
  58978. }
  58979. }
  58980. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  58981. if (colors && vertexColor) {
  58982. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  58983. }
  58984. return instance;
  58985. }
  58986. // line system creation
  58987. var useVertexColor = (colors) ? true : false;
  58988. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  58989. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  58990. vertexData.applyToMesh(lineSystem, options.updatable);
  58991. return lineSystem;
  58992. };
  58993. /**
  58994. * Creates a line mesh.
  58995. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  58996. * 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.
  58997. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  58998. * The parameter `points` is an array successive Vector3.
  58999. * 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
  59000. * The optional parameter `colors` is an array of successive Color4, one per line point.
  59001. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  59002. * When updating an instance, remember that only point positions can change, not the number of points.
  59003. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59004. */
  59005. MeshBuilder.CreateLines = function (name, options, scene) {
  59006. if (scene === void 0) { scene = null; }
  59007. var colors = (options.colors) ? [options.colors] : null;
  59008. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  59009. return lines;
  59010. };
  59011. /**
  59012. * Creates a dashed line mesh.
  59013. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  59014. * 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.
  59015. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  59016. * The parameter `points` is an array successive Vector3.
  59017. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  59018. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  59019. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  59020. * 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
  59021. * When updating an instance, remember that only point positions can change, not the number of points.
  59022. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59023. */
  59024. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  59025. if (scene === void 0) { scene = null; }
  59026. var points = options.points;
  59027. var instance = options.instance;
  59028. var gapSize = options.gapSize || 1;
  59029. var dashSize = options.dashSize || 3;
  59030. if (instance) {
  59031. var positionFunction = function (positions) {
  59032. var curvect = BABYLON.Vector3.Zero();
  59033. var nbSeg = positions.length / 6;
  59034. var lg = 0;
  59035. var nb = 0;
  59036. var shft = 0;
  59037. var dashshft = 0;
  59038. var curshft = 0;
  59039. var p = 0;
  59040. var i = 0;
  59041. var j = 0;
  59042. for (i = 0; i < points.length - 1; i++) {
  59043. points[i + 1].subtractToRef(points[i], curvect);
  59044. lg += curvect.length();
  59045. }
  59046. shft = lg / nbSeg;
  59047. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  59048. for (i = 0; i < points.length - 1; i++) {
  59049. points[i + 1].subtractToRef(points[i], curvect);
  59050. nb = Math.floor(curvect.length() / shft);
  59051. curvect.normalize();
  59052. j = 0;
  59053. while (j < nb && p < positions.length) {
  59054. curshft = shft * j;
  59055. positions[p] = points[i].x + curshft * curvect.x;
  59056. positions[p + 1] = points[i].y + curshft * curvect.y;
  59057. positions[p + 2] = points[i].z + curshft * curvect.z;
  59058. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  59059. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  59060. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  59061. p += 6;
  59062. j++;
  59063. }
  59064. }
  59065. while (p < positions.length) {
  59066. positions[p] = points[i].x;
  59067. positions[p + 1] = points[i].y;
  59068. positions[p + 2] = points[i].z;
  59069. p += 3;
  59070. }
  59071. };
  59072. instance.updateMeshPositions(positionFunction, false);
  59073. return instance;
  59074. }
  59075. // dashed lines creation
  59076. var dashedLines = new BABYLON.LinesMesh(name, scene);
  59077. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  59078. vertexData.applyToMesh(dashedLines, options.updatable);
  59079. dashedLines.dashSize = dashSize;
  59080. dashedLines.gapSize = gapSize;
  59081. return dashedLines;
  59082. };
  59083. /**
  59084. * Creates an extruded shape mesh.
  59085. * 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.
  59086. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  59087. *
  59088. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  59089. * 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
  59090. * extruded along the Z axis.
  59091. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  59092. * 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.
  59093. * The parameter `scale` (float, default 1) is the value to scale the shape.
  59094. * 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
  59095. * 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
  59096. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  59097. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59098. * 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).
  59099. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  59100. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  59101. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59102. */
  59103. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  59104. if (scene === void 0) { scene = null; }
  59105. var path = options.path;
  59106. var shape = options.shape;
  59107. var scale = options.scale || 1;
  59108. var rotation = options.rotation || 0;
  59109. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  59110. var updatable = options.updatable;
  59111. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59112. var instance = options.instance || null;
  59113. var invertUV = options.invertUV || false;
  59114. 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);
  59115. };
  59116. /**
  59117. * Creates an custom extruded shape mesh.
  59118. * 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.
  59119. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  59120. *
  59121. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  59122. * 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
  59123. * extruded along the Z axis.
  59124. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  59125. * 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
  59126. * and the distance of this point from the begining of the path :
  59127. * ```javascript
  59128. * var rotationFunction = function(i, distance) {
  59129. * // do things
  59130. * return rotationValue; }
  59131. * ```
  59132. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  59133. * 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
  59134. * and the distance of this point from the begining of the path :
  59135. * ```javascript
  59136. * var scaleFunction = function(i, distance) {
  59137. * // do things
  59138. * return scaleValue;}
  59139. * ```
  59140. * It must returns a float value that will be the scale value applied to the shape on each path point.
  59141. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  59142. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  59143. * 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
  59144. * 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
  59145. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  59146. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59147. * 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).
  59148. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  59149. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  59150. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59151. */
  59152. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  59153. var path = options.path;
  59154. var shape = options.shape;
  59155. var scaleFunction = options.scaleFunction || (function () { return 1; });
  59156. var rotationFunction = options.rotationFunction || (function () { return 0; });
  59157. var ribbonCloseArray = options.ribbonCloseArray || false;
  59158. var ribbonClosePath = options.ribbonClosePath || false;
  59159. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  59160. var updatable = options.updatable;
  59161. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59162. var instance = options.instance;
  59163. var invertUV = options.invertUV || false;
  59164. 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);
  59165. };
  59166. /**
  59167. * Creates lathe mesh.
  59168. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  59169. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  59170. *
  59171. * 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
  59172. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  59173. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  59174. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  59175. * 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.
  59176. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  59177. * 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
  59178. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59179. * 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).
  59180. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  59181. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  59182. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59183. */
  59184. MeshBuilder.CreateLathe = function (name, options, scene) {
  59185. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  59186. var closed = (options.closed === undefined) ? true : options.closed;
  59187. var shape = options.shape;
  59188. var radius = options.radius || 1;
  59189. var tessellation = options.tessellation || 64;
  59190. var updatable = options.updatable;
  59191. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59192. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  59193. var pi2 = Math.PI * 2;
  59194. var paths = new Array();
  59195. var invertUV = options.invertUV || false;
  59196. var i = 0;
  59197. var p = 0;
  59198. var step = pi2 / tessellation * arc;
  59199. var rotated;
  59200. var path = new Array();
  59201. ;
  59202. for (i = 0; i <= tessellation; i++) {
  59203. var path = [];
  59204. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  59205. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  59206. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  59207. }
  59208. for (p = 0; p < shape.length; p++) {
  59209. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  59210. path.push(rotated);
  59211. }
  59212. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  59213. 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));
  59214. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  59215. }
  59216. paths.push(path);
  59217. }
  59218. // lathe ribbon
  59219. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  59220. return lathe;
  59221. };
  59222. /**
  59223. * Creates a plane mesh.
  59224. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  59225. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  59226. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  59227. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  59228. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59229. * 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).
  59230. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  59231. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59232. */
  59233. MeshBuilder.CreatePlane = function (name, options, scene) {
  59234. var plane = new BABYLON.Mesh(name, scene);
  59235. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59236. plane._originalBuilderSideOrientation = options.sideOrientation;
  59237. var vertexData = BABYLON.VertexData.CreatePlane(options);
  59238. vertexData.applyToMesh(plane, options.updatable);
  59239. if (options.sourcePlane) {
  59240. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  59241. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  59242. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  59243. plane.rotate(vectorProduct, product);
  59244. }
  59245. return plane;
  59246. };
  59247. /**
  59248. * Creates a ground mesh.
  59249. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  59250. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  59251. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  59252. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59253. */
  59254. MeshBuilder.CreateGround = function (name, options, scene) {
  59255. var ground = new BABYLON.GroundMesh(name, scene);
  59256. ground._setReady(false);
  59257. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  59258. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  59259. ground._width = options.width || 1;
  59260. ground._height = options.height || 1;
  59261. ground._maxX = ground._width / 2;
  59262. ground._maxZ = ground._height / 2;
  59263. ground._minX = -ground._maxX;
  59264. ground._minZ = -ground._maxZ;
  59265. var vertexData = BABYLON.VertexData.CreateGround(options);
  59266. vertexData.applyToMesh(ground, options.updatable);
  59267. ground._setReady(true);
  59268. return ground;
  59269. };
  59270. /**
  59271. * Creates a tiled ground mesh.
  59272. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  59273. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  59274. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  59275. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  59276. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  59277. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  59278. * numbers of subdivisions on the ground width and height of each tile.
  59279. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59280. */
  59281. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  59282. var tiledGround = new BABYLON.Mesh(name, scene);
  59283. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  59284. vertexData.applyToMesh(tiledGround, options.updatable);
  59285. return tiledGround;
  59286. };
  59287. /**
  59288. * Creates a ground mesh from a height map.
  59289. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  59290. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  59291. * The parameter `url` sets the URL of the height map image resource.
  59292. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  59293. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  59294. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  59295. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  59296. * 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.
  59297. * 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).
  59298. * This function is passed the newly built mesh :
  59299. * ```javascript
  59300. * function(mesh) { // do things
  59301. * return; }
  59302. * ```
  59303. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59304. */
  59305. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  59306. var width = options.width || 10.0;
  59307. var height = options.height || 10.0;
  59308. var subdivisions = options.subdivisions || 1 | 0;
  59309. var minHeight = options.minHeight || 0.0;
  59310. var maxHeight = options.maxHeight || 1.0;
  59311. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  59312. var updatable = options.updatable;
  59313. var onReady = options.onReady;
  59314. var ground = new BABYLON.GroundMesh(name, scene);
  59315. ground._subdivisionsX = subdivisions;
  59316. ground._subdivisionsY = subdivisions;
  59317. ground._width = width;
  59318. ground._height = height;
  59319. ground._maxX = ground._width / 2.0;
  59320. ground._maxZ = ground._height / 2.0;
  59321. ground._minX = -ground._maxX;
  59322. ground._minZ = -ground._maxZ;
  59323. ground._setReady(false);
  59324. var onload = function (img) {
  59325. // Getting height map data
  59326. var canvas = document.createElement("canvas");
  59327. var context = canvas.getContext("2d");
  59328. if (!context) {
  59329. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  59330. }
  59331. if (scene.isDisposed) {
  59332. return;
  59333. }
  59334. var bufferWidth = img.width;
  59335. var bufferHeight = img.height;
  59336. canvas.width = bufferWidth;
  59337. canvas.height = bufferHeight;
  59338. context.drawImage(img, 0, 0);
  59339. // Create VertexData from map data
  59340. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  59341. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  59342. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  59343. width: width, height: height,
  59344. subdivisions: subdivisions,
  59345. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  59346. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  59347. });
  59348. vertexData.applyToMesh(ground, updatable);
  59349. //execute ready callback, if set
  59350. if (onReady) {
  59351. onReady(ground);
  59352. }
  59353. ground._setReady(true);
  59354. };
  59355. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  59356. return ground;
  59357. };
  59358. /**
  59359. * Creates a polygon mesh.
  59360. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  59361. * 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.
  59362. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59363. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59364. * 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).
  59365. * Remember you can only change the shape positions, not their number when updating a polygon.
  59366. */
  59367. MeshBuilder.CreatePolygon = function (name, options, scene) {
  59368. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59369. var shape = options.shape;
  59370. var holes = options.holes || [];
  59371. var depth = options.depth || 0;
  59372. var contours = [];
  59373. var hole = [];
  59374. for (var i = 0; i < shape.length; i++) {
  59375. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  59376. }
  59377. var epsilon = 0.00000001;
  59378. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  59379. contours.pop();
  59380. }
  59381. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  59382. for (var hNb = 0; hNb < holes.length; hNb++) {
  59383. hole = [];
  59384. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  59385. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  59386. }
  59387. polygonTriangulation.addHole(hole);
  59388. }
  59389. var polygon = polygonTriangulation.build(options.updatable, depth);
  59390. polygon._originalBuilderSideOrientation = options.sideOrientation;
  59391. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  59392. vertexData.applyToMesh(polygon, options.updatable);
  59393. return polygon;
  59394. };
  59395. ;
  59396. /**
  59397. * Creates an extruded polygon mesh, with depth in the Y direction.
  59398. * 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).
  59399. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  59400. */
  59401. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  59402. return MeshBuilder.CreatePolygon(name, options, scene);
  59403. };
  59404. ;
  59405. /**
  59406. * Creates a tube mesh.
  59407. * 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.
  59408. *
  59409. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  59410. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  59411. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  59412. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  59413. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  59414. * 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.
  59415. * It must return a radius value (positive float) :
  59416. * ```javascript
  59417. * var radiusFunction = function(i, distance) {
  59418. * // do things
  59419. * return radius; }
  59420. * ```
  59421. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  59422. * 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
  59423. * 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
  59424. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59425. * 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).
  59426. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  59427. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  59428. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59429. */
  59430. MeshBuilder.CreateTube = function (name, options, scene) {
  59431. var path = options.path;
  59432. var instance = options.instance;
  59433. var radius = 1.0;
  59434. if (instance) {
  59435. radius = instance.radius;
  59436. }
  59437. if (options.radius !== undefined) {
  59438. radius = options.radius;
  59439. }
  59440. ;
  59441. var tessellation = options.tessellation || 64 | 0;
  59442. var radiusFunction = options.radiusFunction || null;
  59443. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  59444. var invertUV = options.invertUV || false;
  59445. var updatable = options.updatable;
  59446. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59447. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  59448. // tube geometry
  59449. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  59450. var tangents = path3D.getTangents();
  59451. var normals = path3D.getNormals();
  59452. var distances = path3D.getDistances();
  59453. var pi2 = Math.PI * 2;
  59454. var step = pi2 / tessellation * arc;
  59455. var returnRadius = function () { return radius; };
  59456. var radiusFunctionFinal = radiusFunction || returnRadius;
  59457. var circlePath;
  59458. var rad;
  59459. var normal;
  59460. var rotated;
  59461. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  59462. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  59463. for (var i = 0; i < path.length; i++) {
  59464. rad = radiusFunctionFinal(i, distances[i]); // current radius
  59465. circlePath = Array(); // current circle array
  59466. normal = normals[i]; // current normal
  59467. for (var t = 0; t < tessellation; t++) {
  59468. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  59469. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  59470. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  59471. rotated.scaleInPlace(rad).addInPlace(path[i]);
  59472. circlePath[t] = rotated;
  59473. }
  59474. circlePaths[index] = circlePath;
  59475. index++;
  59476. }
  59477. // cap
  59478. var capPath = function (nbPoints, pathIndex) {
  59479. var pointCap = Array();
  59480. for (var i = 0; i < nbPoints; i++) {
  59481. pointCap.push(path[pathIndex]);
  59482. }
  59483. return pointCap;
  59484. };
  59485. switch (cap) {
  59486. case BABYLON.Mesh.NO_CAP:
  59487. break;
  59488. case BABYLON.Mesh.CAP_START:
  59489. circlePaths[0] = capPath(tessellation, 0);
  59490. circlePaths[1] = circlePaths[2].slice(0);
  59491. break;
  59492. case BABYLON.Mesh.CAP_END:
  59493. circlePaths[index] = circlePaths[index - 1].slice(0);
  59494. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  59495. break;
  59496. case BABYLON.Mesh.CAP_ALL:
  59497. circlePaths[0] = capPath(tessellation, 0);
  59498. circlePaths[1] = circlePaths[2].slice(0);
  59499. circlePaths[index] = circlePaths[index - 1].slice(0);
  59500. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  59501. break;
  59502. default:
  59503. break;
  59504. }
  59505. return circlePaths;
  59506. };
  59507. var path3D;
  59508. var pathArray;
  59509. if (instance) {
  59510. var arc = options.arc || instance.arc;
  59511. path3D = (instance.path3D).update(path);
  59512. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  59513. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  59514. instance.path3D = path3D;
  59515. instance.pathArray = pathArray;
  59516. instance.arc = arc;
  59517. instance.radius = radius;
  59518. return instance;
  59519. }
  59520. // tube creation
  59521. path3D = new BABYLON.Path3D(path);
  59522. var newPathArray = new Array();
  59523. cap = (cap < 0 || cap > 3) ? 0 : cap;
  59524. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  59525. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  59526. tube.pathArray = pathArray;
  59527. tube.path3D = path3D;
  59528. tube.tessellation = tessellation;
  59529. tube.cap = cap;
  59530. tube.arc = options.arc;
  59531. tube.radius = radius;
  59532. return tube;
  59533. };
  59534. /**
  59535. * Creates a polyhedron mesh.
  59536. *
  59537. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  59538. * 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
  59539. * to choose the wanted type.
  59540. * The parameter `size` (positive float, default 1) sets the polygon size.
  59541. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  59542. * 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`.
  59543. * 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
  59544. * 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)`).
  59545. * 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
  59546. * 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.
  59547. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59548. * 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).
  59549. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  59550. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59551. */
  59552. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  59553. var polyhedron = new BABYLON.Mesh(name, scene);
  59554. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59555. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  59556. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  59557. vertexData.applyToMesh(polyhedron, options.updatable);
  59558. return polyhedron;
  59559. };
  59560. /**
  59561. * Creates a decal mesh.
  59562. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  59563. * 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.
  59564. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  59565. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  59566. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  59567. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  59568. */
  59569. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  59570. var indices = sourceMesh.getIndices();
  59571. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59572. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  59573. var position = options.position || BABYLON.Vector3.Zero();
  59574. var normal = options.normal || BABYLON.Vector3.Up();
  59575. var size = options.size || BABYLON.Vector3.One();
  59576. var angle = options.angle || 0;
  59577. // Getting correct rotation
  59578. if (!normal) {
  59579. var target = new BABYLON.Vector3(0, 0, 1);
  59580. var camera = sourceMesh.getScene().activeCamera;
  59581. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  59582. normal = camera.globalPosition.subtract(cameraWorldTarget);
  59583. }
  59584. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  59585. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  59586. var pitch = Math.atan2(normal.y, len);
  59587. // Matrix
  59588. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  59589. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  59590. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  59591. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  59592. var vertexData = new BABYLON.VertexData();
  59593. vertexData.indices = [];
  59594. vertexData.positions = [];
  59595. vertexData.normals = [];
  59596. vertexData.uvs = [];
  59597. var currentVertexDataIndex = 0;
  59598. var extractDecalVector3 = function (indexId) {
  59599. var result = new BABYLON.PositionNormalVertex();
  59600. if (!indices || !positions || !normals) {
  59601. return result;
  59602. }
  59603. var vertexId = indices[indexId];
  59604. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  59605. // Send vector to decal local world
  59606. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  59607. // Get normal
  59608. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  59609. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  59610. return result;
  59611. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  59612. var clip = function (vertices, axis) {
  59613. if (vertices.length === 0) {
  59614. return vertices;
  59615. }
  59616. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  59617. var clipVertices = function (v0, v1) {
  59618. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  59619. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  59620. };
  59621. var result = new Array();
  59622. for (var index = 0; index < vertices.length; index += 3) {
  59623. var v1Out;
  59624. var v2Out;
  59625. var v3Out;
  59626. var total = 0;
  59627. var nV1 = null;
  59628. var nV2 = null;
  59629. var nV3 = null;
  59630. var nV4 = null;
  59631. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  59632. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  59633. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  59634. v1Out = d1 > 0;
  59635. v2Out = d2 > 0;
  59636. v3Out = d3 > 0;
  59637. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  59638. switch (total) {
  59639. case 0:
  59640. result.push(vertices[index]);
  59641. result.push(vertices[index + 1]);
  59642. result.push(vertices[index + 2]);
  59643. break;
  59644. case 1:
  59645. if (v1Out) {
  59646. nV1 = vertices[index + 1];
  59647. nV2 = vertices[index + 2];
  59648. nV3 = clipVertices(vertices[index], nV1);
  59649. nV4 = clipVertices(vertices[index], nV2);
  59650. }
  59651. if (v2Out) {
  59652. nV1 = vertices[index];
  59653. nV2 = vertices[index + 2];
  59654. nV3 = clipVertices(vertices[index + 1], nV1);
  59655. nV4 = clipVertices(vertices[index + 1], nV2);
  59656. result.push(nV3);
  59657. result.push(nV2.clone());
  59658. result.push(nV1.clone());
  59659. result.push(nV2.clone());
  59660. result.push(nV3.clone());
  59661. result.push(nV4);
  59662. break;
  59663. }
  59664. if (v3Out) {
  59665. nV1 = vertices[index];
  59666. nV2 = vertices[index + 1];
  59667. nV3 = clipVertices(vertices[index + 2], nV1);
  59668. nV4 = clipVertices(vertices[index + 2], nV2);
  59669. }
  59670. if (nV1 && nV2 && nV3 && nV4) {
  59671. result.push(nV1.clone());
  59672. result.push(nV2.clone());
  59673. result.push(nV3);
  59674. result.push(nV4);
  59675. result.push(nV3.clone());
  59676. result.push(nV2.clone());
  59677. }
  59678. break;
  59679. case 2:
  59680. if (!v1Out) {
  59681. nV1 = vertices[index].clone();
  59682. nV2 = clipVertices(nV1, vertices[index + 1]);
  59683. nV3 = clipVertices(nV1, vertices[index + 2]);
  59684. result.push(nV1);
  59685. result.push(nV2);
  59686. result.push(nV3);
  59687. }
  59688. if (!v2Out) {
  59689. nV1 = vertices[index + 1].clone();
  59690. nV2 = clipVertices(nV1, vertices[index + 2]);
  59691. nV3 = clipVertices(nV1, vertices[index]);
  59692. result.push(nV1);
  59693. result.push(nV2);
  59694. result.push(nV3);
  59695. }
  59696. if (!v3Out) {
  59697. nV1 = vertices[index + 2].clone();
  59698. nV2 = clipVertices(nV1, vertices[index]);
  59699. nV3 = clipVertices(nV1, vertices[index + 1]);
  59700. result.push(nV1);
  59701. result.push(nV2);
  59702. result.push(nV3);
  59703. }
  59704. break;
  59705. case 3:
  59706. break;
  59707. }
  59708. }
  59709. return result;
  59710. };
  59711. for (var index = 0; index < indices.length; index += 3) {
  59712. var faceVertices = new Array();
  59713. faceVertices.push(extractDecalVector3(index));
  59714. faceVertices.push(extractDecalVector3(index + 1));
  59715. faceVertices.push(extractDecalVector3(index + 2));
  59716. // Clip
  59717. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  59718. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  59719. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  59720. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  59721. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  59722. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  59723. if (faceVertices.length === 0) {
  59724. continue;
  59725. }
  59726. // Add UVs and get back to world
  59727. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  59728. var vertex = faceVertices[vIndex];
  59729. //TODO check for Int32Array | Uint32Array | Uint16Array
  59730. vertexData.indices.push(currentVertexDataIndex);
  59731. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  59732. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  59733. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  59734. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  59735. currentVertexDataIndex++;
  59736. }
  59737. }
  59738. // Return mesh
  59739. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  59740. vertexData.applyToMesh(decal);
  59741. decal.position = position.clone();
  59742. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  59743. return decal;
  59744. };
  59745. // Privates
  59746. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  59747. // extrusion geometry
  59748. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  59749. var tangents = path3D.getTangents();
  59750. var normals = path3D.getNormals();
  59751. var binormals = path3D.getBinormals();
  59752. var distances = path3D.getDistances();
  59753. var angle = 0;
  59754. var returnScale = function () { return scale !== null ? scale : 1; };
  59755. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  59756. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  59757. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  59758. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  59759. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  59760. for (var i = 0; i < curve.length; i++) {
  59761. var shapePath = new Array();
  59762. var angleStep = rotate(i, distances[i]);
  59763. var scaleRatio = scl(i, distances[i]);
  59764. for (var p = 0; p < shape.length; p++) {
  59765. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  59766. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  59767. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  59768. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  59769. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  59770. shapePath[p] = rotated;
  59771. }
  59772. shapePaths[index] = shapePath;
  59773. angle += angleStep;
  59774. index++;
  59775. }
  59776. // cap
  59777. var capPath = function (shapePath) {
  59778. var pointCap = Array();
  59779. var barycenter = BABYLON.Vector3.Zero();
  59780. var i;
  59781. for (i = 0; i < shapePath.length; i++) {
  59782. barycenter.addInPlace(shapePath[i]);
  59783. }
  59784. barycenter.scaleInPlace(1.0 / shapePath.length);
  59785. for (i = 0; i < shapePath.length; i++) {
  59786. pointCap.push(barycenter);
  59787. }
  59788. return pointCap;
  59789. };
  59790. switch (cap) {
  59791. case BABYLON.Mesh.NO_CAP:
  59792. break;
  59793. case BABYLON.Mesh.CAP_START:
  59794. shapePaths[0] = capPath(shapePaths[2]);
  59795. shapePaths[1] = shapePaths[2];
  59796. break;
  59797. case BABYLON.Mesh.CAP_END:
  59798. shapePaths[index] = shapePaths[index - 1];
  59799. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  59800. break;
  59801. case BABYLON.Mesh.CAP_ALL:
  59802. shapePaths[0] = capPath(shapePaths[2]);
  59803. shapePaths[1] = shapePaths[2];
  59804. shapePaths[index] = shapePaths[index - 1];
  59805. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  59806. break;
  59807. default:
  59808. break;
  59809. }
  59810. return shapePaths;
  59811. };
  59812. var path3D;
  59813. var pathArray;
  59814. if (instance) {
  59815. path3D = (instance.path3D).update(curve);
  59816. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  59817. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  59818. return instance;
  59819. }
  59820. // extruded shape creation
  59821. path3D = new BABYLON.Path3D(curve);
  59822. var newShapePaths = new Array();
  59823. cap = (cap < 0 || cap > 3) ? 0 : cap;
  59824. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  59825. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  59826. extrudedGeneric.pathArray = pathArray;
  59827. extrudedGeneric.path3D = path3D;
  59828. extrudedGeneric.cap = cap;
  59829. return extrudedGeneric;
  59830. };
  59831. return MeshBuilder;
  59832. }());
  59833. BABYLON.MeshBuilder = MeshBuilder;
  59834. })(BABYLON || (BABYLON = {}));
  59835. //# sourceMappingURL=babylon.meshBuilder.js.map
  59836. "use strict";
  59837. var BABYLON;
  59838. (function (BABYLON) {
  59839. /**
  59840. * Draco compression (https://google.github.io/draco/)
  59841. */
  59842. var DracoCompression = /** @class */ (function () {
  59843. /**
  59844. * Constructor
  59845. * @param numWorkers The number of workers for async operations
  59846. */
  59847. function DracoCompression(numWorkers) {
  59848. if (numWorkers === void 0) { numWorkers = (navigator.hardwareConcurrency || 4); }
  59849. var workerBlobUrl = URL && URL.createObjectURL && URL.createObjectURL(new Blob(["(" + DracoCompression._Worker.toString() + ")()"], { type: "application/javascript" }));
  59850. if (!workerBlobUrl || !Worker) {
  59851. BABYLON.Tools.Error("Draco Compression disabled. The current context doesn't support worker creation or URL.createObjectURL");
  59852. return;
  59853. }
  59854. var workers = new Array(numWorkers);
  59855. for (var i = 0; i < workers.length; i++) {
  59856. var worker = new Worker(workerBlobUrl);
  59857. worker.postMessage({ id: "initDecoder", url: DracoCompression.DecoderUrl });
  59858. workers[i] = worker;
  59859. }
  59860. this._workerPool = new BABYLON.WorkerPool(workers);
  59861. }
  59862. /**
  59863. * Stop all async operations and release resources.
  59864. */
  59865. DracoCompression.prototype.dispose = function () {
  59866. this._workerPool.dispose();
  59867. delete this._workerPool;
  59868. };
  59869. /**
  59870. * Decode Draco compressed mesh data to vertex data.
  59871. * @param data The array buffer view for the Draco compression data
  59872. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  59873. * @returns A promise that resolves with the decoded vertex data
  59874. */
  59875. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  59876. var _this = this;
  59877. return new Promise(function (resolve, reject) {
  59878. _this._workerPool.push(function (worker, onComplete) {
  59879. var vertexData = new BABYLON.VertexData();
  59880. var onError = function (error) {
  59881. worker.removeEventListener("error", onError);
  59882. worker.removeEventListener("message", onMessage);
  59883. reject(error);
  59884. onComplete();
  59885. };
  59886. var onMessage = function (message) {
  59887. if (message.data === "done") {
  59888. worker.removeEventListener("error", onError);
  59889. worker.removeEventListener("message", onMessage);
  59890. resolve(vertexData);
  59891. onComplete();
  59892. }
  59893. else if (message.data.id === "indices") {
  59894. vertexData.indices = message.data.value;
  59895. }
  59896. else {
  59897. vertexData.set(message.data.value, message.data.id);
  59898. }
  59899. };
  59900. worker.addEventListener("error", onError);
  59901. worker.addEventListener("message", onMessage);
  59902. var dataCopy = new Uint8Array(data.byteLength);
  59903. dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
  59904. worker.postMessage({ id: "decodeMesh", data: dataCopy, attributes: attributes }, [dataCopy.buffer]);
  59905. });
  59906. });
  59907. };
  59908. /**
  59909. * The worker function that gets converted to a blob url to pass into a worker.
  59910. */
  59911. DracoCompression._Worker = function () {
  59912. // self is actually a DedicatedWorkerGlobalScope
  59913. var _self = self;
  59914. var decodeMesh = function (data, attributes) {
  59915. var dracoModule = new DracoDecoderModule();
  59916. var buffer = new dracoModule.DecoderBuffer();
  59917. buffer.Init(data, data.byteLength);
  59918. var decoder = new dracoModule.Decoder();
  59919. var geometry;
  59920. var status;
  59921. try {
  59922. var type = decoder.GetEncodedGeometryType(buffer);
  59923. switch (type) {
  59924. case dracoModule.TRIANGULAR_MESH:
  59925. geometry = new dracoModule.Mesh();
  59926. status = decoder.DecodeBufferToMesh(buffer, geometry);
  59927. break;
  59928. case dracoModule.POINT_CLOUD:
  59929. geometry = new dracoModule.PointCloud();
  59930. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  59931. break;
  59932. default:
  59933. throw new Error("Invalid geometry type " + type);
  59934. }
  59935. if (!status.ok() || !geometry.ptr) {
  59936. throw new Error(status.error_msg());
  59937. }
  59938. var numPoints = geometry.num_points();
  59939. if (type === dracoModule.TRIANGULAR_MESH) {
  59940. var numFaces = geometry.num_faces();
  59941. var faceIndices = new dracoModule.DracoInt32Array();
  59942. try {
  59943. var indices = new Uint32Array(numFaces * 3);
  59944. for (var i = 0; i < numFaces; i++) {
  59945. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  59946. var offset = i * 3;
  59947. indices[offset + 0] = faceIndices.GetValue(0);
  59948. indices[offset + 1] = faceIndices.GetValue(1);
  59949. indices[offset + 2] = faceIndices.GetValue(2);
  59950. }
  59951. _self.postMessage({ id: "indices", value: indices }, [indices.buffer]);
  59952. }
  59953. finally {
  59954. dracoModule.destroy(faceIndices);
  59955. }
  59956. }
  59957. for (var kind in attributes) {
  59958. var uniqueId = attributes[kind];
  59959. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  59960. var dracoData = new dracoModule.DracoFloat32Array();
  59961. try {
  59962. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  59963. var babylonData = new Float32Array(numPoints * attribute.num_components());
  59964. for (var i = 0; i < babylonData.length; i++) {
  59965. babylonData[i] = dracoData.GetValue(i);
  59966. }
  59967. _self.postMessage({ id: kind, value: babylonData }, [babylonData.buffer]);
  59968. }
  59969. finally {
  59970. dracoModule.destroy(dracoData);
  59971. }
  59972. }
  59973. }
  59974. finally {
  59975. if (geometry) {
  59976. dracoModule.destroy(geometry);
  59977. }
  59978. dracoModule.destroy(decoder);
  59979. dracoModule.destroy(buffer);
  59980. }
  59981. _self.postMessage("done");
  59982. };
  59983. _self.onmessage = function (event) {
  59984. switch (event.data.id) {
  59985. case "initDecoder": {
  59986. importScripts(event.data.url);
  59987. break;
  59988. }
  59989. case "decodeMesh": {
  59990. decodeMesh(event.data.data, event.data.attributes);
  59991. break;
  59992. }
  59993. }
  59994. };
  59995. };
  59996. DracoCompression._GetDefaultDecoderUrl = function () {
  59997. if (!BABYLON.Tools.IsWindowObjectExist()) {
  59998. return null;
  59999. }
  60000. for (var i = 0; i < document.scripts.length; i++) {
  60001. if (document.scripts[i].type === "text/x-draco-decoder") {
  60002. return document.scripts[i].src;
  60003. }
  60004. }
  60005. return null;
  60006. };
  60007. /**
  60008. * Gets the url to the draco decoder if available.
  60009. */
  60010. DracoCompression.DecoderUrl = DracoCompression._GetDefaultDecoderUrl();
  60011. return DracoCompression;
  60012. }());
  60013. BABYLON.DracoCompression = DracoCompression;
  60014. })(BABYLON || (BABYLON = {}));
  60015. //# sourceMappingURL=babylon.dracoCompression.js.map
  60016. "use strict";
  60017. var BABYLON;
  60018. (function (BABYLON) {
  60019. var AudioEngine = /** @class */ (function () {
  60020. function AudioEngine() {
  60021. this._audioContext = null;
  60022. this._audioContextInitialized = false;
  60023. this.canUseWebAudio = false;
  60024. this.WarnedWebAudioUnsupported = false;
  60025. this.unlocked = false;
  60026. this.isMP3supported = false;
  60027. this.isOGGsupported = false;
  60028. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  60029. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  60030. this.canUseWebAudio = true;
  60031. }
  60032. var audioElem = document.createElement('audio');
  60033. try {
  60034. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  60035. this.isMP3supported = true;
  60036. }
  60037. }
  60038. catch (e) {
  60039. // protect error during capability check.
  60040. }
  60041. try {
  60042. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  60043. this.isOGGsupported = true;
  60044. }
  60045. }
  60046. catch (e) {
  60047. // protect error during capability check.
  60048. }
  60049. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  60050. this._unlockiOSaudio();
  60051. }
  60052. else {
  60053. this.unlocked = true;
  60054. }
  60055. }
  60056. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  60057. get: function () {
  60058. if (!this._audioContextInitialized) {
  60059. this._initializeAudioContext();
  60060. }
  60061. return this._audioContext;
  60062. },
  60063. enumerable: true,
  60064. configurable: true
  60065. });
  60066. AudioEngine.prototype._unlockiOSaudio = function () {
  60067. var _this = this;
  60068. var unlockaudio = function () {
  60069. if (!_this.audioContext) {
  60070. return;
  60071. }
  60072. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  60073. var source = _this.audioContext.createBufferSource();
  60074. source.buffer = buffer;
  60075. source.connect(_this.audioContext.destination);
  60076. source.start(0);
  60077. setTimeout(function () {
  60078. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  60079. _this.unlocked = true;
  60080. window.removeEventListener('touchend', unlockaudio, false);
  60081. if (_this.onAudioUnlocked) {
  60082. _this.onAudioUnlocked();
  60083. }
  60084. }
  60085. }, 0);
  60086. };
  60087. window.addEventListener('touchend', unlockaudio, false);
  60088. };
  60089. AudioEngine.prototype._initializeAudioContext = function () {
  60090. try {
  60091. if (this.canUseWebAudio) {
  60092. this._audioContext = new AudioContext();
  60093. // create a global volume gain node
  60094. this.masterGain = this._audioContext.createGain();
  60095. this.masterGain.gain.value = 1;
  60096. this.masterGain.connect(this._audioContext.destination);
  60097. this._audioContextInitialized = true;
  60098. }
  60099. }
  60100. catch (e) {
  60101. this.canUseWebAudio = false;
  60102. BABYLON.Tools.Error("Web Audio: " + e.message);
  60103. }
  60104. };
  60105. AudioEngine.prototype.dispose = function () {
  60106. if (this.canUseWebAudio && this._audioContextInitialized) {
  60107. if (this._connectedAnalyser && this._audioContext) {
  60108. this._connectedAnalyser.stopDebugCanvas();
  60109. this._connectedAnalyser.dispose();
  60110. this.masterGain.disconnect();
  60111. this.masterGain.connect(this._audioContext.destination);
  60112. this._connectedAnalyser = null;
  60113. }
  60114. this.masterGain.gain.value = 1;
  60115. }
  60116. this.WarnedWebAudioUnsupported = false;
  60117. };
  60118. AudioEngine.prototype.getGlobalVolume = function () {
  60119. if (this.canUseWebAudio && this._audioContextInitialized) {
  60120. return this.masterGain.gain.value;
  60121. }
  60122. else {
  60123. return -1;
  60124. }
  60125. };
  60126. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  60127. if (this.canUseWebAudio && this._audioContextInitialized) {
  60128. this.masterGain.gain.value = newVolume;
  60129. }
  60130. };
  60131. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  60132. if (this._connectedAnalyser) {
  60133. this._connectedAnalyser.stopDebugCanvas();
  60134. }
  60135. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  60136. this._connectedAnalyser = analyser;
  60137. this.masterGain.disconnect();
  60138. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  60139. }
  60140. };
  60141. return AudioEngine;
  60142. }());
  60143. BABYLON.AudioEngine = AudioEngine;
  60144. })(BABYLON || (BABYLON = {}));
  60145. //# sourceMappingURL=babylon.audioEngine.js.map
  60146. "use strict";
  60147. var BABYLON;
  60148. (function (BABYLON) {
  60149. var Sound = /** @class */ (function () {
  60150. /**
  60151. * Create a sound and attach it to a scene
  60152. * @param name Name of your sound
  60153. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  60154. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  60155. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  60156. */
  60157. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  60158. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  60159. var _this = this;
  60160. this.autoplay = false;
  60161. this.loop = false;
  60162. this.useCustomAttenuation = false;
  60163. this.spatialSound = false;
  60164. this.refDistance = 1;
  60165. this.rolloffFactor = 1;
  60166. this.maxDistance = 100;
  60167. this.distanceModel = "linear";
  60168. this._panningModel = "equalpower";
  60169. this._playbackRate = 1;
  60170. this._streaming = false;
  60171. this._startTime = 0;
  60172. this._startOffset = 0;
  60173. this._position = BABYLON.Vector3.Zero();
  60174. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  60175. this._volume = 1;
  60176. this._isReadyToPlay = false;
  60177. this.isPlaying = false;
  60178. this.isPaused = false;
  60179. this._isDirectional = false;
  60180. // Used if you'd like to create a directional sound.
  60181. // If not set, the sound will be omnidirectional
  60182. this._coneInnerAngle = 360;
  60183. this._coneOuterAngle = 360;
  60184. this._coneOuterGain = 0;
  60185. this._isOutputConnected = false;
  60186. this._urlType = "Unknown";
  60187. this.name = name;
  60188. this._scene = scene;
  60189. this._readyToPlayCallback = readyToPlayCallback;
  60190. // Default custom attenuation function is a linear attenuation
  60191. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  60192. if (currentDistance < maxDistance) {
  60193. return currentVolume * (1 - currentDistance / maxDistance);
  60194. }
  60195. else {
  60196. return 0;
  60197. }
  60198. };
  60199. if (options) {
  60200. this.autoplay = options.autoplay || false;
  60201. this.loop = options.loop || false;
  60202. // if volume === 0, we need another way to check this option
  60203. if (options.volume !== undefined) {
  60204. this._volume = options.volume;
  60205. }
  60206. this.spatialSound = options.spatialSound || false;
  60207. this.maxDistance = options.maxDistance || 100;
  60208. this.useCustomAttenuation = options.useCustomAttenuation || false;
  60209. this.rolloffFactor = options.rolloffFactor || 1;
  60210. this.refDistance = options.refDistance || 1;
  60211. this.distanceModel = options.distanceModel || "linear";
  60212. this._playbackRate = options.playbackRate || 1;
  60213. this._streaming = options.streaming || false;
  60214. }
  60215. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  60216. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  60217. this._soundGain.gain.value = this._volume;
  60218. this._inputAudioNode = this._soundGain;
  60219. this._ouputAudioNode = this._soundGain;
  60220. if (this.spatialSound) {
  60221. this._createSpatialParameters();
  60222. }
  60223. this._scene.mainSoundTrack.AddSound(this);
  60224. var validParameter = true;
  60225. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  60226. if (urlOrArrayBuffer) {
  60227. try {
  60228. if (typeof (urlOrArrayBuffer) === "string")
  60229. this._urlType = "String";
  60230. if (Array.isArray(urlOrArrayBuffer))
  60231. this._urlType = "Array";
  60232. if (urlOrArrayBuffer instanceof ArrayBuffer)
  60233. this._urlType = "ArrayBuffer";
  60234. var urls = [];
  60235. var codecSupportedFound = false;
  60236. switch (this._urlType) {
  60237. case "ArrayBuffer":
  60238. if (urlOrArrayBuffer.byteLength > 0) {
  60239. codecSupportedFound = true;
  60240. this._soundLoaded(urlOrArrayBuffer);
  60241. }
  60242. break;
  60243. case "String":
  60244. urls.push(urlOrArrayBuffer);
  60245. case "Array":
  60246. if (urls.length === 0)
  60247. urls = urlOrArrayBuffer;
  60248. // If we found a supported format, we load it immediately and stop the loop
  60249. for (var i = 0; i < urls.length; i++) {
  60250. var url = urls[i];
  60251. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  60252. codecSupportedFound = true;
  60253. }
  60254. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  60255. codecSupportedFound = true;
  60256. }
  60257. if (url.indexOf(".wav", url.length - 4) !== -1) {
  60258. codecSupportedFound = true;
  60259. }
  60260. if (url.indexOf("blob:") !== -1) {
  60261. codecSupportedFound = true;
  60262. }
  60263. if (codecSupportedFound) {
  60264. // Loading sound using XHR2
  60265. if (!this._streaming) {
  60266. this._scene._loadFile(url, function (data) {
  60267. _this._soundLoaded(data);
  60268. }, undefined, true, true, function (exception) {
  60269. if (exception) {
  60270. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  60271. }
  60272. BABYLON.Tools.Error("Sound creation aborted.");
  60273. _this._scene.mainSoundTrack.RemoveSound(_this);
  60274. });
  60275. }
  60276. else {
  60277. this._htmlAudioElement = new Audio(url);
  60278. this._htmlAudioElement.controls = false;
  60279. this._htmlAudioElement.loop = this.loop;
  60280. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  60281. this._htmlAudioElement.preload = "auto";
  60282. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  60283. _this._isReadyToPlay = true;
  60284. if (_this.autoplay) {
  60285. _this.play();
  60286. }
  60287. if (_this._readyToPlayCallback) {
  60288. _this._readyToPlayCallback();
  60289. }
  60290. });
  60291. document.body.appendChild(this._htmlAudioElement);
  60292. }
  60293. break;
  60294. }
  60295. }
  60296. break;
  60297. default:
  60298. validParameter = false;
  60299. break;
  60300. }
  60301. if (!validParameter) {
  60302. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  60303. }
  60304. else {
  60305. if (!codecSupportedFound) {
  60306. this._isReadyToPlay = true;
  60307. // Simulating a ready to play event to avoid breaking code path
  60308. if (this._readyToPlayCallback) {
  60309. window.setTimeout(function () {
  60310. if (_this._readyToPlayCallback) {
  60311. _this._readyToPlayCallback();
  60312. }
  60313. }, 1000);
  60314. }
  60315. }
  60316. }
  60317. }
  60318. catch (ex) {
  60319. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  60320. this._scene.mainSoundTrack.RemoveSound(this);
  60321. }
  60322. }
  60323. }
  60324. else {
  60325. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  60326. this._scene.mainSoundTrack.AddSound(this);
  60327. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  60328. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  60329. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  60330. }
  60331. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  60332. if (this._readyToPlayCallback) {
  60333. window.setTimeout(function () {
  60334. if (_this._readyToPlayCallback) {
  60335. _this._readyToPlayCallback();
  60336. }
  60337. }, 1000);
  60338. }
  60339. }
  60340. }
  60341. Sound.prototype.dispose = function () {
  60342. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  60343. if (this.isPlaying) {
  60344. this.stop();
  60345. }
  60346. this._isReadyToPlay = false;
  60347. if (this.soundTrackId === -1) {
  60348. this._scene.mainSoundTrack.RemoveSound(this);
  60349. }
  60350. else {
  60351. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  60352. }
  60353. if (this._soundGain) {
  60354. this._soundGain.disconnect();
  60355. this._soundGain = null;
  60356. }
  60357. if (this._soundPanner) {
  60358. this._soundPanner.disconnect();
  60359. this._soundPanner = null;
  60360. }
  60361. if (this._soundSource) {
  60362. this._soundSource.disconnect();
  60363. this._soundSource = null;
  60364. }
  60365. this._audioBuffer = null;
  60366. if (this._htmlAudioElement) {
  60367. this._htmlAudioElement.pause();
  60368. this._htmlAudioElement.src = "";
  60369. document.body.removeChild(this._htmlAudioElement);
  60370. }
  60371. if (this._connectedMesh && this._registerFunc) {
  60372. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  60373. this._connectedMesh = null;
  60374. }
  60375. }
  60376. };
  60377. Sound.prototype.isReady = function () {
  60378. return this._isReadyToPlay;
  60379. };
  60380. Sound.prototype._soundLoaded = function (audioData) {
  60381. var _this = this;
  60382. if (!BABYLON.Engine.audioEngine.audioContext) {
  60383. return;
  60384. }
  60385. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  60386. _this._audioBuffer = buffer;
  60387. _this._isReadyToPlay = true;
  60388. if (_this.autoplay) {
  60389. _this.play();
  60390. }
  60391. if (_this._readyToPlayCallback) {
  60392. _this._readyToPlayCallback();
  60393. }
  60394. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  60395. };
  60396. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  60397. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  60398. this._audioBuffer = audioBuffer;
  60399. this._isReadyToPlay = true;
  60400. }
  60401. };
  60402. Sound.prototype.updateOptions = function (options) {
  60403. if (options) {
  60404. this.loop = options.loop || this.loop;
  60405. this.maxDistance = options.maxDistance || this.maxDistance;
  60406. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  60407. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  60408. this.refDistance = options.refDistance || this.refDistance;
  60409. this.distanceModel = options.distanceModel || this.distanceModel;
  60410. this._playbackRate = options.playbackRate || this._playbackRate;
  60411. this._updateSpatialParameters();
  60412. if (this.isPlaying) {
  60413. if (this._streaming) {
  60414. this._htmlAudioElement.playbackRate = this._playbackRate;
  60415. }
  60416. else {
  60417. if (this._soundSource) {
  60418. this._soundSource.playbackRate.value = this._playbackRate;
  60419. }
  60420. }
  60421. }
  60422. }
  60423. };
  60424. Sound.prototype._createSpatialParameters = function () {
  60425. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  60426. if (this._scene.headphone) {
  60427. this._panningModel = "HRTF";
  60428. }
  60429. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  60430. this._updateSpatialParameters();
  60431. this._soundPanner.connect(this._ouputAudioNode);
  60432. this._inputAudioNode = this._soundPanner;
  60433. }
  60434. };
  60435. Sound.prototype._updateSpatialParameters = function () {
  60436. if (this.spatialSound && this._soundPanner) {
  60437. if (this.useCustomAttenuation) {
  60438. // Tricks to disable in a way embedded Web Audio attenuation
  60439. this._soundPanner.distanceModel = "linear";
  60440. this._soundPanner.maxDistance = Number.MAX_VALUE;
  60441. this._soundPanner.refDistance = 1;
  60442. this._soundPanner.rolloffFactor = 1;
  60443. this._soundPanner.panningModel = this._panningModel;
  60444. }
  60445. else {
  60446. this._soundPanner.distanceModel = this.distanceModel;
  60447. this._soundPanner.maxDistance = this.maxDistance;
  60448. this._soundPanner.refDistance = this.refDistance;
  60449. this._soundPanner.rolloffFactor = this.rolloffFactor;
  60450. this._soundPanner.panningModel = this._panningModel;
  60451. }
  60452. }
  60453. };
  60454. Sound.prototype.switchPanningModelToHRTF = function () {
  60455. this._panningModel = "HRTF";
  60456. this._switchPanningModel();
  60457. };
  60458. Sound.prototype.switchPanningModelToEqualPower = function () {
  60459. this._panningModel = "equalpower";
  60460. this._switchPanningModel();
  60461. };
  60462. Sound.prototype._switchPanningModel = function () {
  60463. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  60464. this._soundPanner.panningModel = this._panningModel;
  60465. }
  60466. };
  60467. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  60468. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  60469. if (this._isOutputConnected) {
  60470. this._ouputAudioNode.disconnect();
  60471. }
  60472. this._ouputAudioNode.connect(soundTrackAudioNode);
  60473. this._isOutputConnected = true;
  60474. }
  60475. };
  60476. /**
  60477. * Transform this sound into a directional source
  60478. * @param coneInnerAngle Size of the inner cone in degree
  60479. * @param coneOuterAngle Size of the outer cone in degree
  60480. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  60481. */
  60482. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  60483. if (coneOuterAngle < coneInnerAngle) {
  60484. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  60485. return;
  60486. }
  60487. this._coneInnerAngle = coneInnerAngle;
  60488. this._coneOuterAngle = coneOuterAngle;
  60489. this._coneOuterGain = coneOuterGain;
  60490. this._isDirectional = true;
  60491. if (this.isPlaying && this.loop) {
  60492. this.stop();
  60493. this.play();
  60494. }
  60495. };
  60496. Sound.prototype.setPosition = function (newPosition) {
  60497. this._position = newPosition;
  60498. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  60499. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  60500. }
  60501. };
  60502. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  60503. this._localDirection = newLocalDirection;
  60504. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  60505. this._updateDirection();
  60506. }
  60507. };
  60508. Sound.prototype._updateDirection = function () {
  60509. if (!this._connectedMesh || !this._soundPanner) {
  60510. return;
  60511. }
  60512. var mat = this._connectedMesh.getWorldMatrix();
  60513. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  60514. direction.normalize();
  60515. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  60516. };
  60517. Sound.prototype.updateDistanceFromListener = function () {
  60518. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  60519. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  60520. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  60521. }
  60522. };
  60523. Sound.prototype.setAttenuationFunction = function (callback) {
  60524. this._customAttenuationFunction = callback;
  60525. };
  60526. /**
  60527. * Play the sound
  60528. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  60529. * @param offset (optional) Start the sound setting it at a specific time
  60530. */
  60531. Sound.prototype.play = function (time, offset) {
  60532. var _this = this;
  60533. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  60534. try {
  60535. if (this._startOffset < 0) {
  60536. time = -this._startOffset;
  60537. this._startOffset = 0;
  60538. }
  60539. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  60540. if (!this._soundSource || !this._streamingSource) {
  60541. if (this.spatialSound && this._soundPanner) {
  60542. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  60543. if (this._isDirectional) {
  60544. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  60545. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  60546. this._soundPanner.coneOuterGain = this._coneOuterGain;
  60547. if (this._connectedMesh) {
  60548. this._updateDirection();
  60549. }
  60550. else {
  60551. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  60552. }
  60553. }
  60554. }
  60555. }
  60556. if (this._streaming) {
  60557. if (!this._streamingSource) {
  60558. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  60559. this._htmlAudioElement.onended = function () { _this._onended(); };
  60560. this._htmlAudioElement.playbackRate = this._playbackRate;
  60561. }
  60562. this._streamingSource.disconnect();
  60563. this._streamingSource.connect(this._inputAudioNode);
  60564. this._htmlAudioElement.play();
  60565. }
  60566. else {
  60567. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  60568. this._soundSource.buffer = this._audioBuffer;
  60569. this._soundSource.connect(this._inputAudioNode);
  60570. this._soundSource.loop = this.loop;
  60571. this._soundSource.playbackRate.value = this._playbackRate;
  60572. this._soundSource.onended = function () { _this._onended(); };
  60573. if (this._soundSource.buffer) {
  60574. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  60575. }
  60576. }
  60577. this._startTime = startTime;
  60578. this.isPlaying = true;
  60579. this.isPaused = false;
  60580. }
  60581. catch (ex) {
  60582. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  60583. }
  60584. }
  60585. };
  60586. Sound.prototype._onended = function () {
  60587. this.isPlaying = false;
  60588. if (this.onended) {
  60589. this.onended();
  60590. }
  60591. };
  60592. /**
  60593. * Stop the sound
  60594. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  60595. */
  60596. Sound.prototype.stop = function (time) {
  60597. if (this.isPlaying) {
  60598. if (this._streaming) {
  60599. this._htmlAudioElement.pause();
  60600. // Test needed for Firefox or it will generate an Invalid State Error
  60601. if (this._htmlAudioElement.currentTime > 0) {
  60602. this._htmlAudioElement.currentTime = 0;
  60603. }
  60604. }
  60605. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  60606. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  60607. this._soundSource.stop(stopTime);
  60608. this._soundSource.onended = function () { };
  60609. if (!this.isPaused) {
  60610. this._startOffset = 0;
  60611. }
  60612. }
  60613. this.isPlaying = false;
  60614. }
  60615. };
  60616. Sound.prototype.pause = function () {
  60617. if (this.isPlaying) {
  60618. this.isPaused = true;
  60619. if (this._streaming) {
  60620. this._htmlAudioElement.pause();
  60621. }
  60622. else if (BABYLON.Engine.audioEngine.audioContext) {
  60623. this.stop(0);
  60624. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  60625. }
  60626. }
  60627. };
  60628. Sound.prototype.setVolume = function (newVolume, time) {
  60629. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  60630. if (time && BABYLON.Engine.audioEngine.audioContext) {
  60631. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  60632. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  60633. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  60634. }
  60635. else {
  60636. this._soundGain.gain.value = newVolume;
  60637. }
  60638. }
  60639. this._volume = newVolume;
  60640. };
  60641. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  60642. this._playbackRate = newPlaybackRate;
  60643. if (this.isPlaying) {
  60644. if (this._streaming) {
  60645. this._htmlAudioElement.playbackRate = this._playbackRate;
  60646. }
  60647. else if (this._soundSource) {
  60648. this._soundSource.playbackRate.value = this._playbackRate;
  60649. }
  60650. }
  60651. };
  60652. Sound.prototype.getVolume = function () {
  60653. return this._volume;
  60654. };
  60655. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  60656. var _this = this;
  60657. if (this._connectedMesh && this._registerFunc) {
  60658. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  60659. this._registerFunc = null;
  60660. }
  60661. this._connectedMesh = meshToConnectTo;
  60662. if (!this.spatialSound) {
  60663. this.spatialSound = true;
  60664. this._createSpatialParameters();
  60665. if (this.isPlaying && this.loop) {
  60666. this.stop();
  60667. this.play();
  60668. }
  60669. }
  60670. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  60671. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  60672. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  60673. };
  60674. Sound.prototype.detachFromMesh = function () {
  60675. if (this._connectedMesh && this._registerFunc) {
  60676. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  60677. this._registerFunc = null;
  60678. this._connectedMesh = null;
  60679. }
  60680. };
  60681. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  60682. if (!node.getBoundingInfo) {
  60683. return;
  60684. }
  60685. var mesh = node;
  60686. var boundingInfo = mesh.getBoundingInfo();
  60687. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  60688. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  60689. this._updateDirection();
  60690. }
  60691. };
  60692. Sound.prototype.clone = function () {
  60693. var _this = this;
  60694. if (!this._streaming) {
  60695. var setBufferAndRun = function () {
  60696. if (_this._isReadyToPlay) {
  60697. clonedSound._audioBuffer = _this.getAudioBuffer();
  60698. clonedSound._isReadyToPlay = true;
  60699. if (clonedSound.autoplay) {
  60700. clonedSound.play();
  60701. }
  60702. }
  60703. else {
  60704. window.setTimeout(setBufferAndRun, 300);
  60705. }
  60706. };
  60707. var currentOptions = {
  60708. autoplay: this.autoplay, loop: this.loop,
  60709. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  60710. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  60711. refDistance: this.refDistance, distanceModel: this.distanceModel
  60712. };
  60713. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  60714. if (this.useCustomAttenuation) {
  60715. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  60716. }
  60717. clonedSound.setPosition(this._position);
  60718. clonedSound.setPlaybackRate(this._playbackRate);
  60719. setBufferAndRun();
  60720. return clonedSound;
  60721. }
  60722. else {
  60723. return null;
  60724. }
  60725. };
  60726. Sound.prototype.getAudioBuffer = function () {
  60727. return this._audioBuffer;
  60728. };
  60729. Sound.prototype.serialize = function () {
  60730. var serializationObject = {
  60731. name: this.name,
  60732. url: this.name,
  60733. autoplay: this.autoplay,
  60734. loop: this.loop,
  60735. volume: this._volume,
  60736. spatialSound: this.spatialSound,
  60737. maxDistance: this.maxDistance,
  60738. rolloffFactor: this.rolloffFactor,
  60739. refDistance: this.refDistance,
  60740. distanceModel: this.distanceModel,
  60741. playbackRate: this._playbackRate,
  60742. panningModel: this._panningModel,
  60743. soundTrackId: this.soundTrackId
  60744. };
  60745. if (this.spatialSound) {
  60746. if (this._connectedMesh)
  60747. serializationObject.connectedMeshId = this._connectedMesh.id;
  60748. serializationObject.position = this._position.asArray();
  60749. serializationObject.refDistance = this.refDistance;
  60750. serializationObject.distanceModel = this.distanceModel;
  60751. serializationObject.isDirectional = this._isDirectional;
  60752. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  60753. serializationObject.coneInnerAngle = this._coneInnerAngle;
  60754. serializationObject.coneOuterAngle = this._coneOuterAngle;
  60755. serializationObject.coneOuterGain = this._coneOuterGain;
  60756. }
  60757. return serializationObject;
  60758. };
  60759. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  60760. var soundName = parsedSound.name;
  60761. var soundUrl;
  60762. if (parsedSound.url) {
  60763. soundUrl = rootUrl + parsedSound.url;
  60764. }
  60765. else {
  60766. soundUrl = rootUrl + soundName;
  60767. }
  60768. var options = {
  60769. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  60770. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  60771. rolloffFactor: parsedSound.rolloffFactor,
  60772. refDistance: parsedSound.refDistance,
  60773. distanceModel: parsedSound.distanceModel,
  60774. playbackRate: parsedSound.playbackRate
  60775. };
  60776. var newSound;
  60777. if (!sourceSound) {
  60778. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  60779. scene._addPendingData(newSound);
  60780. }
  60781. else {
  60782. var setBufferAndRun = function () {
  60783. if (sourceSound._isReadyToPlay) {
  60784. newSound._audioBuffer = sourceSound.getAudioBuffer();
  60785. newSound._isReadyToPlay = true;
  60786. if (newSound.autoplay) {
  60787. newSound.play();
  60788. }
  60789. }
  60790. else {
  60791. window.setTimeout(setBufferAndRun, 300);
  60792. }
  60793. };
  60794. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  60795. setBufferAndRun();
  60796. }
  60797. if (parsedSound.position) {
  60798. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  60799. newSound.setPosition(soundPosition);
  60800. }
  60801. if (parsedSound.isDirectional) {
  60802. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  60803. if (parsedSound.localDirectionToMesh) {
  60804. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  60805. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  60806. }
  60807. }
  60808. if (parsedSound.connectedMeshId) {
  60809. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  60810. if (connectedMesh) {
  60811. newSound.attachToMesh(connectedMesh);
  60812. }
  60813. }
  60814. return newSound;
  60815. };
  60816. return Sound;
  60817. }());
  60818. BABYLON.Sound = Sound;
  60819. })(BABYLON || (BABYLON = {}));
  60820. //# sourceMappingURL=babylon.sound.js.map
  60821. "use strict";
  60822. var BABYLON;
  60823. (function (BABYLON) {
  60824. var SoundTrack = /** @class */ (function () {
  60825. function SoundTrack(scene, options) {
  60826. this.id = -1;
  60827. this._isMainTrack = false;
  60828. this._isInitialized = false;
  60829. this._scene = scene;
  60830. this.soundCollection = new Array();
  60831. this._options = options;
  60832. if (!this._isMainTrack) {
  60833. this._scene.soundTracks.push(this);
  60834. this.id = this._scene.soundTracks.length - 1;
  60835. }
  60836. }
  60837. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  60838. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  60839. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  60840. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  60841. if (this._options) {
  60842. if (this._options.volume) {
  60843. this._outputAudioNode.gain.value = this._options.volume;
  60844. }
  60845. if (this._options.mainTrack) {
  60846. this._isMainTrack = this._options.mainTrack;
  60847. }
  60848. }
  60849. this._isInitialized = true;
  60850. }
  60851. };
  60852. SoundTrack.prototype.dispose = function () {
  60853. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  60854. if (this._connectedAnalyser) {
  60855. this._connectedAnalyser.stopDebugCanvas();
  60856. }
  60857. while (this.soundCollection.length) {
  60858. this.soundCollection[0].dispose();
  60859. }
  60860. if (this._outputAudioNode) {
  60861. this._outputAudioNode.disconnect();
  60862. }
  60863. this._outputAudioNode = null;
  60864. }
  60865. };
  60866. SoundTrack.prototype.AddSound = function (sound) {
  60867. if (!this._isInitialized) {
  60868. this._initializeSoundTrackAudioGraph();
  60869. }
  60870. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  60871. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  60872. }
  60873. if (sound.soundTrackId) {
  60874. if (sound.soundTrackId === -1) {
  60875. this._scene.mainSoundTrack.RemoveSound(sound);
  60876. }
  60877. else {
  60878. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  60879. }
  60880. }
  60881. this.soundCollection.push(sound);
  60882. sound.soundTrackId = this.id;
  60883. };
  60884. SoundTrack.prototype.RemoveSound = function (sound) {
  60885. var index = this.soundCollection.indexOf(sound);
  60886. if (index !== -1) {
  60887. this.soundCollection.splice(index, 1);
  60888. }
  60889. };
  60890. SoundTrack.prototype.setVolume = function (newVolume) {
  60891. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  60892. this._outputAudioNode.gain.value = newVolume;
  60893. }
  60894. };
  60895. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  60896. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  60897. for (var i = 0; i < this.soundCollection.length; i++) {
  60898. this.soundCollection[i].switchPanningModelToHRTF();
  60899. }
  60900. }
  60901. };
  60902. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  60903. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  60904. for (var i = 0; i < this.soundCollection.length; i++) {
  60905. this.soundCollection[i].switchPanningModelToEqualPower();
  60906. }
  60907. }
  60908. };
  60909. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  60910. if (this._connectedAnalyser) {
  60911. this._connectedAnalyser.stopDebugCanvas();
  60912. }
  60913. this._connectedAnalyser = analyser;
  60914. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  60915. this._outputAudioNode.disconnect();
  60916. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  60917. }
  60918. };
  60919. return SoundTrack;
  60920. }());
  60921. BABYLON.SoundTrack = SoundTrack;
  60922. })(BABYLON || (BABYLON = {}));
  60923. //# sourceMappingURL=babylon.soundtrack.js.map
  60924. "use strict";
  60925. var BABYLON;
  60926. (function (BABYLON) {
  60927. var Analyser = /** @class */ (function () {
  60928. function Analyser(scene) {
  60929. this.SMOOTHING = 0.75;
  60930. this.FFT_SIZE = 512;
  60931. this.BARGRAPHAMPLITUDE = 256;
  60932. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  60933. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  60934. this._scene = scene;
  60935. this._audioEngine = BABYLON.Engine.audioEngine;
  60936. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  60937. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  60938. this._webAudioAnalyser.minDecibels = -140;
  60939. this._webAudioAnalyser.maxDecibels = 0;
  60940. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  60941. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  60942. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  60943. }
  60944. }
  60945. Analyser.prototype.getFrequencyBinCount = function () {
  60946. if (this._audioEngine.canUseWebAudio) {
  60947. return this._webAudioAnalyser.frequencyBinCount;
  60948. }
  60949. else {
  60950. return 0;
  60951. }
  60952. };
  60953. Analyser.prototype.getByteFrequencyData = function () {
  60954. if (this._audioEngine.canUseWebAudio) {
  60955. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  60956. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  60957. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  60958. }
  60959. return this._byteFreqs;
  60960. };
  60961. Analyser.prototype.getByteTimeDomainData = function () {
  60962. if (this._audioEngine.canUseWebAudio) {
  60963. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  60964. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  60965. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  60966. }
  60967. return this._byteTime;
  60968. };
  60969. Analyser.prototype.getFloatFrequencyData = function () {
  60970. if (this._audioEngine.canUseWebAudio) {
  60971. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  60972. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  60973. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  60974. }
  60975. return this._floatFreqs;
  60976. };
  60977. Analyser.prototype.drawDebugCanvas = function () {
  60978. var _this = this;
  60979. if (this._audioEngine.canUseWebAudio) {
  60980. if (!this._debugCanvas) {
  60981. this._debugCanvas = document.createElement("canvas");
  60982. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  60983. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  60984. this._debugCanvas.style.position = "absolute";
  60985. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  60986. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  60987. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  60988. document.body.appendChild(this._debugCanvas);
  60989. this._registerFunc = function () {
  60990. _this.drawDebugCanvas();
  60991. };
  60992. this._scene.registerBeforeRender(this._registerFunc);
  60993. }
  60994. if (this._registerFunc && this._debugCanvasContext) {
  60995. var workingArray = this.getByteFrequencyData();
  60996. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  60997. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  60998. // Draw the frequency domain chart.
  60999. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  61000. var value = workingArray[i];
  61001. var percent = value / this.BARGRAPHAMPLITUDE;
  61002. var height = this.DEBUGCANVASSIZE.height * percent;
  61003. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  61004. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  61005. var hue = i / this.getFrequencyBinCount() * 360;
  61006. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  61007. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  61008. }
  61009. }
  61010. }
  61011. };
  61012. Analyser.prototype.stopDebugCanvas = function () {
  61013. if (this._debugCanvas) {
  61014. if (this._registerFunc) {
  61015. this._scene.unregisterBeforeRender(this._registerFunc);
  61016. this._registerFunc = null;
  61017. }
  61018. document.body.removeChild(this._debugCanvas);
  61019. this._debugCanvas = null;
  61020. this._debugCanvasContext = null;
  61021. }
  61022. };
  61023. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  61024. if (this._audioEngine.canUseWebAudio) {
  61025. inputAudioNode.connect(this._webAudioAnalyser);
  61026. this._webAudioAnalyser.connect(outputAudioNode);
  61027. }
  61028. };
  61029. Analyser.prototype.dispose = function () {
  61030. if (this._audioEngine.canUseWebAudio) {
  61031. this._webAudioAnalyser.disconnect();
  61032. }
  61033. };
  61034. return Analyser;
  61035. }());
  61036. BABYLON.Analyser = Analyser;
  61037. })(BABYLON || (BABYLON = {}));
  61038. //# sourceMappingURL=babylon.analyser.js.map
  61039. "use strict";
  61040. var BABYLON;
  61041. (function (BABYLON) {
  61042. var CubeTexture = /** @class */ (function (_super) {
  61043. __extends(CubeTexture, _super);
  61044. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  61045. if (extensions === void 0) { extensions = null; }
  61046. if (noMipmap === void 0) { noMipmap = false; }
  61047. if (files === void 0) { files = null; }
  61048. if (onLoad === void 0) { onLoad = null; }
  61049. if (onError === void 0) { onError = null; }
  61050. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  61051. if (prefiltered === void 0) { prefiltered = false; }
  61052. if (forcedExtension === void 0) { forcedExtension = null; }
  61053. var _this = _super.call(this, scene) || this;
  61054. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  61055. /**
  61056. * Gets or sets the center of the bounding box associated with the cube texture
  61057. * It must define where the camera used to render the texture was set
  61058. */
  61059. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  61060. _this.name = rootUrl;
  61061. _this.url = rootUrl;
  61062. _this._noMipmap = noMipmap;
  61063. _this.hasAlpha = false;
  61064. _this._format = format;
  61065. _this._prefiltered = prefiltered;
  61066. _this.isCube = true;
  61067. _this._textureMatrix = BABYLON.Matrix.Identity();
  61068. if (prefiltered) {
  61069. _this.gammaSpace = false;
  61070. }
  61071. if (!rootUrl && !files) {
  61072. return _this;
  61073. }
  61074. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  61075. var lastDot = rootUrl.lastIndexOf(".");
  61076. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  61077. var isDDS = (extension === ".dds");
  61078. if (!files) {
  61079. if (!isDDS && !extensions) {
  61080. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  61081. }
  61082. files = [];
  61083. if (extensions) {
  61084. for (var index = 0; index < extensions.length; index++) {
  61085. files.push(rootUrl + extensions[index]);
  61086. }
  61087. }
  61088. }
  61089. _this._files = files;
  61090. if (!_this._texture) {
  61091. if (!scene.useDelayedTextureLoading) {
  61092. if (prefiltered) {
  61093. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  61094. }
  61095. else {
  61096. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  61097. }
  61098. }
  61099. else {
  61100. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  61101. }
  61102. }
  61103. else if (onLoad) {
  61104. if (_this._texture.isReady) {
  61105. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  61106. }
  61107. else {
  61108. _this._texture.onLoadedObservable.add(onLoad);
  61109. }
  61110. }
  61111. return _this;
  61112. }
  61113. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  61114. get: function () {
  61115. return this._boundingBoxSize;
  61116. },
  61117. /**
  61118. * Gets or sets the size of the bounding box associated with the cube texture
  61119. * When defined, the cubemap will switch to local mode
  61120. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  61121. * @example https://www.babylonjs-playground.com/#RNASML
  61122. */
  61123. set: function (value) {
  61124. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  61125. return;
  61126. }
  61127. this._boundingBoxSize = value;
  61128. var scene = this.getScene();
  61129. if (scene) {
  61130. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  61131. }
  61132. },
  61133. enumerable: true,
  61134. configurable: true
  61135. });
  61136. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  61137. var rootUrlKey = "";
  61138. files.forEach(function (url) { return rootUrlKey += url; });
  61139. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  61140. };
  61141. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  61142. if (forcedExtension === void 0) { forcedExtension = null; }
  61143. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  61144. };
  61145. // Methods
  61146. CubeTexture.prototype.delayLoad = function () {
  61147. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  61148. return;
  61149. }
  61150. var scene = this.getScene();
  61151. if (!scene) {
  61152. return;
  61153. }
  61154. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  61155. this._texture = this._getFromCache(this.url, this._noMipmap);
  61156. if (!this._texture) {
  61157. if (this._prefiltered) {
  61158. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  61159. }
  61160. else {
  61161. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  61162. }
  61163. }
  61164. };
  61165. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  61166. return this._textureMatrix;
  61167. };
  61168. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  61169. this._textureMatrix = value;
  61170. };
  61171. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  61172. var texture = BABYLON.SerializationHelper.Parse(function () {
  61173. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  61174. }, parsedTexture, scene);
  61175. // Local Cubemaps
  61176. if (parsedTexture.boundingBoxPosition) {
  61177. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  61178. }
  61179. if (parsedTexture.boundingBoxSize) {
  61180. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  61181. }
  61182. // Animations
  61183. if (parsedTexture.animations) {
  61184. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  61185. var parsedAnimation = parsedTexture.animations[animationIndex];
  61186. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  61187. }
  61188. }
  61189. return texture;
  61190. };
  61191. CubeTexture.prototype.clone = function () {
  61192. var _this = this;
  61193. return BABYLON.SerializationHelper.Clone(function () {
  61194. var scene = _this.getScene();
  61195. if (!scene) {
  61196. return _this;
  61197. }
  61198. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  61199. }, this);
  61200. };
  61201. return CubeTexture;
  61202. }(BABYLON.BaseTexture));
  61203. BABYLON.CubeTexture = CubeTexture;
  61204. })(BABYLON || (BABYLON = {}));
  61205. //# sourceMappingURL=babylon.cubeTexture.js.map
  61206. "use strict";
  61207. var BABYLON;
  61208. (function (BABYLON) {
  61209. var RenderTargetTexture = /** @class */ (function (_super) {
  61210. __extends(RenderTargetTexture, _super);
  61211. /**
  61212. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  61213. * or used a shadow, depth texture...
  61214. * @param name The friendly name of the texture
  61215. * @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)
  61216. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  61217. * @param generateMipMaps True if mip maps need to be generated after render.
  61218. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  61219. * @param type The type of the buffer in the RTT (int, half float, float...)
  61220. * @param isCube True if a cube texture needs to be created
  61221. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  61222. * @param generateDepthBuffer True to generate a depth buffer
  61223. * @param generateStencilBuffer True to generate a stencil buffer
  61224. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  61225. */
  61226. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  61227. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  61228. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  61229. if (isCube === void 0) { isCube = false; }
  61230. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  61231. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  61232. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  61233. if (isMulti === void 0) { isMulti = false; }
  61234. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  61235. _this.isCube = isCube;
  61236. /**
  61237. * Use this list to define the list of mesh you want to render.
  61238. */
  61239. _this.renderList = new Array();
  61240. _this.renderParticles = true;
  61241. _this.renderSprites = false;
  61242. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  61243. _this.ignoreCameraViewport = false;
  61244. // Events
  61245. /**
  61246. * An event triggered when the texture is unbind.
  61247. */
  61248. _this.onBeforeBindObservable = new BABYLON.Observable();
  61249. /**
  61250. * An event triggered when the texture is unbind.
  61251. */
  61252. _this.onAfterUnbindObservable = new BABYLON.Observable();
  61253. /**
  61254. * An event triggered before rendering the texture
  61255. */
  61256. _this.onBeforeRenderObservable = new BABYLON.Observable();
  61257. /**
  61258. * An event triggered after rendering the texture
  61259. */
  61260. _this.onAfterRenderObservable = new BABYLON.Observable();
  61261. /**
  61262. * An event triggered after the texture clear
  61263. */
  61264. _this.onClearObservable = new BABYLON.Observable();
  61265. _this._currentRefreshId = -1;
  61266. _this._refreshRate = 1;
  61267. _this._samples = 1;
  61268. /**
  61269. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  61270. * It must define where the camera used to render the texture is set
  61271. */
  61272. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  61273. scene = _this.getScene();
  61274. if (!scene) {
  61275. return _this;
  61276. }
  61277. _this._engine = scene.getEngine();
  61278. _this.name = name;
  61279. _this.isRenderTarget = true;
  61280. _this._initialSizeParameter = size;
  61281. _this._processSizeParameter(size);
  61282. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  61283. });
  61284. _this._generateMipMaps = generateMipMaps ? true : false;
  61285. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  61286. // Rendering groups
  61287. _this._renderingManager = new BABYLON.RenderingManager(scene);
  61288. if (isMulti) {
  61289. return _this;
  61290. }
  61291. _this._renderTargetOptions = {
  61292. generateMipMaps: generateMipMaps,
  61293. type: type,
  61294. samplingMode: samplingMode,
  61295. generateDepthBuffer: generateDepthBuffer,
  61296. generateStencilBuffer: generateStencilBuffer
  61297. };
  61298. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  61299. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61300. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61301. }
  61302. if (isCube) {
  61303. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  61304. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  61305. _this._textureMatrix = BABYLON.Matrix.Identity();
  61306. }
  61307. else {
  61308. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  61309. }
  61310. return _this;
  61311. }
  61312. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  61313. get: function () {
  61314. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  61315. },
  61316. enumerable: true,
  61317. configurable: true
  61318. });
  61319. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  61320. get: function () {
  61321. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  61322. },
  61323. enumerable: true,
  61324. configurable: true
  61325. });
  61326. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  61327. get: function () {
  61328. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  61329. },
  61330. enumerable: true,
  61331. configurable: true
  61332. });
  61333. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  61334. set: function (callback) {
  61335. if (this._onAfterUnbindObserver) {
  61336. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  61337. }
  61338. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  61339. },
  61340. enumerable: true,
  61341. configurable: true
  61342. });
  61343. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  61344. set: function (callback) {
  61345. if (this._onBeforeRenderObserver) {
  61346. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  61347. }
  61348. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  61349. },
  61350. enumerable: true,
  61351. configurable: true
  61352. });
  61353. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  61354. set: function (callback) {
  61355. if (this._onAfterRenderObserver) {
  61356. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  61357. }
  61358. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  61359. },
  61360. enumerable: true,
  61361. configurable: true
  61362. });
  61363. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  61364. set: function (callback) {
  61365. if (this._onClearObserver) {
  61366. this.onClearObservable.remove(this._onClearObserver);
  61367. }
  61368. this._onClearObserver = this.onClearObservable.add(callback);
  61369. },
  61370. enumerable: true,
  61371. configurable: true
  61372. });
  61373. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  61374. get: function () {
  61375. return this._renderTargetOptions;
  61376. },
  61377. enumerable: true,
  61378. configurable: true
  61379. });
  61380. RenderTargetTexture.prototype._onRatioRescale = function () {
  61381. if (this._sizeRatio) {
  61382. this.resize(this._initialSizeParameter);
  61383. }
  61384. };
  61385. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  61386. get: function () {
  61387. return this._boundingBoxSize;
  61388. },
  61389. /**
  61390. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  61391. * When defined, the cubemap will switch to local mode
  61392. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  61393. * @example https://www.babylonjs-playground.com/#RNASML
  61394. */
  61395. set: function (value) {
  61396. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  61397. return;
  61398. }
  61399. this._boundingBoxSize = value;
  61400. var scene = this.getScene();
  61401. if (scene) {
  61402. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  61403. }
  61404. },
  61405. enumerable: true,
  61406. configurable: true
  61407. });
  61408. /**
  61409. * Creates a depth stencil texture.
  61410. * This is only available in WebGL 2 or with the depth texture extension available.
  61411. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  61412. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  61413. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  61414. */
  61415. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  61416. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  61417. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  61418. if (generateStencil === void 0) { generateStencil = false; }
  61419. if (!this.getScene()) {
  61420. return;
  61421. }
  61422. var engine = this.getScene().getEngine();
  61423. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  61424. bilinearFiltering: bilinearFiltering,
  61425. comparisonFunction: comparisonFunction,
  61426. generateStencil: generateStencil,
  61427. isCube: this.isCube
  61428. });
  61429. engine.setFrameBufferDepthStencilTexture(this);
  61430. };
  61431. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  61432. if (size.ratio) {
  61433. this._sizeRatio = size.ratio;
  61434. this._size = {
  61435. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  61436. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  61437. };
  61438. }
  61439. else {
  61440. this._size = size;
  61441. }
  61442. };
  61443. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  61444. get: function () {
  61445. return this._samples;
  61446. },
  61447. set: function (value) {
  61448. if (this._samples === value) {
  61449. return;
  61450. }
  61451. var scene = this.getScene();
  61452. if (!scene) {
  61453. return;
  61454. }
  61455. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  61456. },
  61457. enumerable: true,
  61458. configurable: true
  61459. });
  61460. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  61461. this._currentRefreshId = -1;
  61462. };
  61463. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  61464. get: function () {
  61465. return this._refreshRate;
  61466. },
  61467. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  61468. set: function (value) {
  61469. this._refreshRate = value;
  61470. this.resetRefreshCounter();
  61471. },
  61472. enumerable: true,
  61473. configurable: true
  61474. });
  61475. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  61476. if (!this._postProcessManager) {
  61477. var scene = this.getScene();
  61478. if (!scene) {
  61479. return;
  61480. }
  61481. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  61482. this._postProcesses = new Array();
  61483. }
  61484. this._postProcesses.push(postProcess);
  61485. this._postProcesses[0].autoClear = false;
  61486. };
  61487. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  61488. if (!this._postProcesses) {
  61489. return;
  61490. }
  61491. if (dispose) {
  61492. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  61493. var postProcess = _a[_i];
  61494. postProcess.dispose();
  61495. }
  61496. }
  61497. this._postProcesses = [];
  61498. };
  61499. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  61500. if (!this._postProcesses) {
  61501. return;
  61502. }
  61503. var index = this._postProcesses.indexOf(postProcess);
  61504. if (index === -1) {
  61505. return;
  61506. }
  61507. this._postProcesses.splice(index, 1);
  61508. if (this._postProcesses.length > 0) {
  61509. this._postProcesses[0].autoClear = false;
  61510. }
  61511. };
  61512. RenderTargetTexture.prototype._shouldRender = function () {
  61513. if (this._currentRefreshId === -1) {
  61514. this._currentRefreshId = 1;
  61515. return true;
  61516. }
  61517. if (this.refreshRate === this._currentRefreshId) {
  61518. this._currentRefreshId = 1;
  61519. return true;
  61520. }
  61521. this._currentRefreshId++;
  61522. return false;
  61523. };
  61524. RenderTargetTexture.prototype.getRenderSize = function () {
  61525. if (this._size.width) {
  61526. return this._size.width;
  61527. }
  61528. return this._size;
  61529. };
  61530. RenderTargetTexture.prototype.getRenderWidth = function () {
  61531. if (this._size.width) {
  61532. return this._size.width;
  61533. }
  61534. return this._size;
  61535. };
  61536. RenderTargetTexture.prototype.getRenderHeight = function () {
  61537. if (this._size.width) {
  61538. return this._size.height;
  61539. }
  61540. return this._size;
  61541. };
  61542. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  61543. get: function () {
  61544. return true;
  61545. },
  61546. enumerable: true,
  61547. configurable: true
  61548. });
  61549. RenderTargetTexture.prototype.scale = function (ratio) {
  61550. var newSize = this.getRenderSize() * ratio;
  61551. this.resize(newSize);
  61552. };
  61553. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  61554. if (this.isCube) {
  61555. return this._textureMatrix;
  61556. }
  61557. return _super.prototype.getReflectionTextureMatrix.call(this);
  61558. };
  61559. RenderTargetTexture.prototype.resize = function (size) {
  61560. this.releaseInternalTexture();
  61561. var scene = this.getScene();
  61562. if (!scene) {
  61563. return;
  61564. }
  61565. this._processSizeParameter(size);
  61566. if (this.isCube) {
  61567. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  61568. }
  61569. else {
  61570. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  61571. }
  61572. };
  61573. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  61574. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  61575. if (dumpForDebug === void 0) { dumpForDebug = false; }
  61576. var scene = this.getScene();
  61577. if (!scene) {
  61578. return;
  61579. }
  61580. var engine = scene.getEngine();
  61581. if (this.useCameraPostProcesses !== undefined) {
  61582. useCameraPostProcess = this.useCameraPostProcesses;
  61583. }
  61584. if (this._waitingRenderList) {
  61585. this.renderList = [];
  61586. for (var index = 0; index < this._waitingRenderList.length; index++) {
  61587. var id = this._waitingRenderList[index];
  61588. var mesh_1 = scene.getMeshByID(id);
  61589. if (mesh_1) {
  61590. this.renderList.push(mesh_1);
  61591. }
  61592. }
  61593. delete this._waitingRenderList;
  61594. }
  61595. // Is predicate defined?
  61596. if (this.renderListPredicate) {
  61597. if (this.renderList) {
  61598. this.renderList.splice(0); // Clear previous renderList
  61599. }
  61600. else {
  61601. this.renderList = [];
  61602. }
  61603. var scene = this.getScene();
  61604. if (!scene) {
  61605. return;
  61606. }
  61607. var sceneMeshes = scene.meshes;
  61608. for (var index = 0; index < sceneMeshes.length; index++) {
  61609. var mesh = sceneMeshes[index];
  61610. if (this.renderListPredicate(mesh)) {
  61611. this.renderList.push(mesh);
  61612. }
  61613. }
  61614. }
  61615. this.onBeforeBindObservable.notifyObservers(this);
  61616. // Set custom projection.
  61617. // Needs to be before binding to prevent changing the aspect ratio.
  61618. var camera;
  61619. if (this.activeCamera) {
  61620. camera = this.activeCamera;
  61621. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  61622. if (this.activeCamera !== scene.activeCamera) {
  61623. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  61624. }
  61625. }
  61626. else {
  61627. camera = scene.activeCamera;
  61628. if (camera) {
  61629. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  61630. }
  61631. }
  61632. // Prepare renderingManager
  61633. this._renderingManager.reset();
  61634. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  61635. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  61636. var sceneRenderId = scene.getRenderId();
  61637. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  61638. var mesh = currentRenderList[meshIndex];
  61639. if (mesh) {
  61640. if (!mesh.isReady(this.refreshRate === 0)) {
  61641. this.resetRefreshCounter();
  61642. continue;
  61643. }
  61644. mesh._preActivateForIntermediateRendering(sceneRenderId);
  61645. var isMasked = void 0;
  61646. if (!this.renderList && camera) {
  61647. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  61648. }
  61649. else {
  61650. isMasked = false;
  61651. }
  61652. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  61653. mesh._activate(sceneRenderId);
  61654. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  61655. var subMesh = mesh.subMeshes[subIndex];
  61656. scene._activeIndices.addCount(subMesh.indexCount, false);
  61657. this._renderingManager.dispatch(subMesh, mesh);
  61658. }
  61659. }
  61660. }
  61661. }
  61662. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  61663. var particleSystem = scene.particleSystems[particleIndex];
  61664. var emitter = particleSystem.emitter;
  61665. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  61666. continue;
  61667. }
  61668. if (currentRenderList.indexOf(emitter) >= 0) {
  61669. this._renderingManager.dispatchParticles(particleSystem);
  61670. }
  61671. }
  61672. if (this.isCube) {
  61673. for (var face = 0; face < 6; face++) {
  61674. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  61675. scene.incrementRenderId();
  61676. scene.resetCachedMaterial();
  61677. }
  61678. }
  61679. else {
  61680. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  61681. }
  61682. this.onAfterUnbindObservable.notifyObservers(this);
  61683. if (scene.activeCamera) {
  61684. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  61685. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  61686. }
  61687. engine.setViewport(scene.activeCamera.viewport);
  61688. }
  61689. scene.resetCachedMaterial();
  61690. };
  61691. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  61692. var minimum = 128;
  61693. var x = renderDimension * scale;
  61694. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  61695. // Ensure we don't exceed the render dimension (while staying POT)
  61696. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  61697. };
  61698. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  61699. var _this = this;
  61700. if (!this._texture) {
  61701. return;
  61702. }
  61703. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  61704. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  61705. });
  61706. };
  61707. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  61708. var scene = this.getScene();
  61709. if (!scene) {
  61710. return;
  61711. }
  61712. var engine = scene.getEngine();
  61713. if (!this._texture) {
  61714. return;
  61715. }
  61716. // Bind
  61717. if (this._postProcessManager) {
  61718. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  61719. }
  61720. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  61721. if (this._texture) {
  61722. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  61723. }
  61724. }
  61725. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  61726. // Clear
  61727. if (this.onClearObservable.hasObservers()) {
  61728. this.onClearObservable.notifyObservers(engine);
  61729. }
  61730. else {
  61731. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  61732. }
  61733. if (!this._doNotChangeAspectRatio) {
  61734. scene.updateTransformMatrix(true);
  61735. }
  61736. // Render
  61737. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  61738. if (this._postProcessManager) {
  61739. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  61740. }
  61741. else if (useCameraPostProcess) {
  61742. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  61743. }
  61744. if (!this._doNotChangeAspectRatio) {
  61745. scene.updateTransformMatrix(true);
  61746. }
  61747. // Dump ?
  61748. if (dumpForDebug) {
  61749. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  61750. }
  61751. // Unbind
  61752. if (!this.isCube || faceIndex === 5) {
  61753. if (this.isCube) {
  61754. if (faceIndex === 5) {
  61755. engine.generateMipMapsForCubemap(this._texture);
  61756. }
  61757. }
  61758. this.unbindFrameBuffer(engine, faceIndex);
  61759. }
  61760. else {
  61761. this.onAfterRenderObservable.notifyObservers(faceIndex);
  61762. }
  61763. };
  61764. /**
  61765. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  61766. * This allowed control for front to back rendering or reversly depending of the special needs.
  61767. *
  61768. * @param renderingGroupId The rendering group id corresponding to its index
  61769. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  61770. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  61771. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  61772. */
  61773. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  61774. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  61775. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  61776. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  61777. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  61778. };
  61779. /**
  61780. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  61781. *
  61782. * @param renderingGroupId The rendering group id corresponding to its index
  61783. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  61784. */
  61785. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  61786. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  61787. };
  61788. RenderTargetTexture.prototype.clone = function () {
  61789. var textureSize = this.getSize();
  61790. 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);
  61791. // Base texture
  61792. newTexture.hasAlpha = this.hasAlpha;
  61793. newTexture.level = this.level;
  61794. // RenderTarget Texture
  61795. newTexture.coordinatesMode = this.coordinatesMode;
  61796. if (this.renderList) {
  61797. newTexture.renderList = this.renderList.slice(0);
  61798. }
  61799. return newTexture;
  61800. };
  61801. RenderTargetTexture.prototype.serialize = function () {
  61802. if (!this.name) {
  61803. return null;
  61804. }
  61805. var serializationObject = _super.prototype.serialize.call(this);
  61806. serializationObject.renderTargetSize = this.getRenderSize();
  61807. serializationObject.renderList = [];
  61808. if (this.renderList) {
  61809. for (var index = 0; index < this.renderList.length; index++) {
  61810. serializationObject.renderList.push(this.renderList[index].id);
  61811. }
  61812. }
  61813. return serializationObject;
  61814. };
  61815. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  61816. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  61817. var objBuffer = this.getInternalTexture();
  61818. var scene = this.getScene();
  61819. if (objBuffer && scene) {
  61820. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  61821. }
  61822. };
  61823. RenderTargetTexture.prototype.dispose = function () {
  61824. if (this._postProcessManager) {
  61825. this._postProcessManager.dispose();
  61826. this._postProcessManager = null;
  61827. }
  61828. this.clearPostProcesses(true);
  61829. if (this._resizeObserver) {
  61830. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  61831. this._resizeObserver = null;
  61832. }
  61833. this.renderList = null;
  61834. // Remove from custom render targets
  61835. var scene = this.getScene();
  61836. if (!scene) {
  61837. return;
  61838. }
  61839. var index = scene.customRenderTargets.indexOf(this);
  61840. if (index >= 0) {
  61841. scene.customRenderTargets.splice(index, 1);
  61842. }
  61843. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  61844. var camera = _a[_i];
  61845. index = camera.customRenderTargets.indexOf(this);
  61846. if (index >= 0) {
  61847. camera.customRenderTargets.splice(index, 1);
  61848. }
  61849. }
  61850. _super.prototype.dispose.call(this);
  61851. };
  61852. RenderTargetTexture.prototype._rebuild = function () {
  61853. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  61854. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  61855. }
  61856. if (this._postProcessManager) {
  61857. this._postProcessManager._rebuild();
  61858. }
  61859. };
  61860. /**
  61861. * Clear the info related to rendering groups preventing retention point in material dispose.
  61862. */
  61863. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  61864. if (this._renderingManager) {
  61865. this._renderingManager.freeRenderingGroups();
  61866. }
  61867. };
  61868. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  61869. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  61870. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  61871. return RenderTargetTexture;
  61872. }(BABYLON.Texture));
  61873. BABYLON.RenderTargetTexture = RenderTargetTexture;
  61874. })(BABYLON || (BABYLON = {}));
  61875. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  61876. "use strict";
  61877. var BABYLON;
  61878. (function (BABYLON) {
  61879. ;
  61880. var MultiRenderTarget = /** @class */ (function (_super) {
  61881. __extends(MultiRenderTarget, _super);
  61882. function MultiRenderTarget(name, size, count, scene, options) {
  61883. var _this = this;
  61884. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  61885. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  61886. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  61887. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  61888. _this._engine = scene.getEngine();
  61889. if (!_this.isSupported) {
  61890. _this.dispose();
  61891. return;
  61892. }
  61893. var types = [];
  61894. var samplingModes = [];
  61895. for (var i = 0; i < count; i++) {
  61896. if (options && options.types && options.types[i] !== undefined) {
  61897. types.push(options.types[i]);
  61898. }
  61899. else {
  61900. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  61901. }
  61902. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  61903. samplingModes.push(options.samplingModes[i]);
  61904. }
  61905. else {
  61906. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61907. }
  61908. }
  61909. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  61910. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  61911. _this._size = size;
  61912. _this._multiRenderTargetOptions = {
  61913. samplingModes: samplingModes,
  61914. generateMipMaps: generateMipMaps,
  61915. generateDepthBuffer: generateDepthBuffer,
  61916. generateStencilBuffer: generateStencilBuffer,
  61917. generateDepthTexture: generateDepthTexture,
  61918. types: types,
  61919. textureCount: count
  61920. };
  61921. _this._createInternalTextures();
  61922. _this._createTextures();
  61923. return _this;
  61924. }
  61925. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  61926. get: function () {
  61927. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  61928. },
  61929. enumerable: true,
  61930. configurable: true
  61931. });
  61932. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  61933. get: function () {
  61934. return this._textures;
  61935. },
  61936. enumerable: true,
  61937. configurable: true
  61938. });
  61939. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  61940. get: function () {
  61941. return this._textures[this._textures.length - 1];
  61942. },
  61943. enumerable: true,
  61944. configurable: true
  61945. });
  61946. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  61947. set: function (wrap) {
  61948. if (this._textures) {
  61949. for (var i = 0; i < this._textures.length; i++) {
  61950. this._textures[i].wrapU = wrap;
  61951. }
  61952. }
  61953. },
  61954. enumerable: true,
  61955. configurable: true
  61956. });
  61957. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  61958. set: function (wrap) {
  61959. if (this._textures) {
  61960. for (var i = 0; i < this._textures.length; i++) {
  61961. this._textures[i].wrapV = wrap;
  61962. }
  61963. }
  61964. },
  61965. enumerable: true,
  61966. configurable: true
  61967. });
  61968. MultiRenderTarget.prototype._rebuild = function () {
  61969. this.releaseInternalTextures();
  61970. this._createInternalTextures();
  61971. for (var i = 0; i < this._internalTextures.length; i++) {
  61972. var texture = this._textures[i];
  61973. texture._texture = this._internalTextures[i];
  61974. }
  61975. // Keeps references to frame buffer and stencil/depth buffer
  61976. this._texture = this._internalTextures[0];
  61977. };
  61978. MultiRenderTarget.prototype._createInternalTextures = function () {
  61979. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  61980. };
  61981. MultiRenderTarget.prototype._createTextures = function () {
  61982. this._textures = [];
  61983. for (var i = 0; i < this._internalTextures.length; i++) {
  61984. var texture = new BABYLON.Texture(null, this.getScene());
  61985. texture._texture = this._internalTextures[i];
  61986. this._textures.push(texture);
  61987. }
  61988. // Keeps references to frame buffer and stencil/depth buffer
  61989. this._texture = this._internalTextures[0];
  61990. };
  61991. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  61992. get: function () {
  61993. return this._samples;
  61994. },
  61995. set: function (value) {
  61996. if (this._samples === value) {
  61997. return;
  61998. }
  61999. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  62000. },
  62001. enumerable: true,
  62002. configurable: true
  62003. });
  62004. MultiRenderTarget.prototype.resize = function (size) {
  62005. this.releaseInternalTextures();
  62006. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  62007. this._createInternalTextures();
  62008. };
  62009. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  62010. var _this = this;
  62011. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  62012. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  62013. });
  62014. };
  62015. MultiRenderTarget.prototype.dispose = function () {
  62016. this.releaseInternalTextures();
  62017. _super.prototype.dispose.call(this);
  62018. };
  62019. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  62020. if (!this._internalTextures) {
  62021. return;
  62022. }
  62023. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  62024. if (this._internalTextures[i] !== undefined) {
  62025. this._internalTextures[i].dispose();
  62026. this._internalTextures.splice(i, 1);
  62027. }
  62028. }
  62029. };
  62030. return MultiRenderTarget;
  62031. }(BABYLON.RenderTargetTexture));
  62032. BABYLON.MultiRenderTarget = MultiRenderTarget;
  62033. })(BABYLON || (BABYLON = {}));
  62034. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  62035. "use strict";
  62036. var BABYLON;
  62037. (function (BABYLON) {
  62038. var MirrorTexture = /** @class */ (function (_super) {
  62039. __extends(MirrorTexture, _super);
  62040. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  62041. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62042. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  62043. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  62044. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  62045. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  62046. _this._transformMatrix = BABYLON.Matrix.Zero();
  62047. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  62048. _this._adaptiveBlurKernel = 0;
  62049. _this._blurKernelX = 0;
  62050. _this._blurKernelY = 0;
  62051. _this._blurRatio = 1.0;
  62052. _this.ignoreCameraViewport = true;
  62053. _this.onBeforeRenderObservable.add(function () {
  62054. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  62055. _this._savedViewMatrix = scene.getViewMatrix();
  62056. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  62057. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  62058. scene.clipPlane = _this.mirrorPlane;
  62059. scene.getEngine().cullBackFaces = false;
  62060. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  62061. });
  62062. _this.onAfterRenderObservable.add(function () {
  62063. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  62064. scene.getEngine().cullBackFaces = true;
  62065. scene._mirroredCameraPosition = null;
  62066. delete scene.clipPlane;
  62067. });
  62068. return _this;
  62069. }
  62070. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  62071. get: function () {
  62072. return this._blurRatio;
  62073. },
  62074. set: function (value) {
  62075. if (this._blurRatio === value) {
  62076. return;
  62077. }
  62078. this._blurRatio = value;
  62079. this._preparePostProcesses();
  62080. },
  62081. enumerable: true,
  62082. configurable: true
  62083. });
  62084. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  62085. set: function (value) {
  62086. this._adaptiveBlurKernel = value;
  62087. this._autoComputeBlurKernel();
  62088. },
  62089. enumerable: true,
  62090. configurable: true
  62091. });
  62092. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  62093. set: function (value) {
  62094. this.blurKernelX = value;
  62095. this.blurKernelY = value;
  62096. },
  62097. enumerable: true,
  62098. configurable: true
  62099. });
  62100. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  62101. get: function () {
  62102. return this._blurKernelX;
  62103. },
  62104. set: function (value) {
  62105. if (this._blurKernelX === value) {
  62106. return;
  62107. }
  62108. this._blurKernelX = value;
  62109. this._preparePostProcesses();
  62110. },
  62111. enumerable: true,
  62112. configurable: true
  62113. });
  62114. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  62115. get: function () {
  62116. return this._blurKernelY;
  62117. },
  62118. set: function (value) {
  62119. if (this._blurKernelY === value) {
  62120. return;
  62121. }
  62122. this._blurKernelY = value;
  62123. this._preparePostProcesses();
  62124. },
  62125. enumerable: true,
  62126. configurable: true
  62127. });
  62128. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  62129. var engine = this.getScene().getEngine();
  62130. var dw = this.getRenderWidth() / engine.getRenderWidth();
  62131. var dh = this.getRenderHeight() / engine.getRenderHeight();
  62132. this.blurKernelX = this._adaptiveBlurKernel * dw;
  62133. this.blurKernelY = this._adaptiveBlurKernel * dh;
  62134. };
  62135. MirrorTexture.prototype._onRatioRescale = function () {
  62136. if (this._sizeRatio) {
  62137. this.resize(this._initialSizeParameter);
  62138. if (!this._adaptiveBlurKernel) {
  62139. this._preparePostProcesses();
  62140. }
  62141. }
  62142. if (this._adaptiveBlurKernel) {
  62143. this._autoComputeBlurKernel();
  62144. }
  62145. };
  62146. MirrorTexture.prototype._preparePostProcesses = function () {
  62147. this.clearPostProcesses(true);
  62148. if (this._blurKernelX && this._blurKernelY) {
  62149. var engine = this.getScene().getEngine();
  62150. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  62151. 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);
  62152. this._blurX.autoClear = false;
  62153. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  62154. this._blurX.inputTexture = this._texture;
  62155. }
  62156. else {
  62157. this._blurX.alwaysForcePOT = true;
  62158. }
  62159. 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);
  62160. this._blurY.autoClear = false;
  62161. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  62162. this.addPostProcess(this._blurX);
  62163. this.addPostProcess(this._blurY);
  62164. }
  62165. else {
  62166. if (this._blurY) {
  62167. this.removePostProcess(this._blurY);
  62168. this._blurY.dispose();
  62169. this._blurY = null;
  62170. }
  62171. if (this._blurX) {
  62172. this.removePostProcess(this._blurX);
  62173. this._blurX.dispose();
  62174. this._blurX = null;
  62175. }
  62176. }
  62177. };
  62178. MirrorTexture.prototype.clone = function () {
  62179. var scene = this.getScene();
  62180. if (!scene) {
  62181. return this;
  62182. }
  62183. var textureSize = this.getSize();
  62184. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  62185. // Base texture
  62186. newTexture.hasAlpha = this.hasAlpha;
  62187. newTexture.level = this.level;
  62188. // Mirror Texture
  62189. newTexture.mirrorPlane = this.mirrorPlane.clone();
  62190. if (this.renderList) {
  62191. newTexture.renderList = this.renderList.slice(0);
  62192. }
  62193. return newTexture;
  62194. };
  62195. MirrorTexture.prototype.serialize = function () {
  62196. if (!this.name) {
  62197. return null;
  62198. }
  62199. var serializationObject = _super.prototype.serialize.call(this);
  62200. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  62201. return serializationObject;
  62202. };
  62203. return MirrorTexture;
  62204. }(BABYLON.RenderTargetTexture));
  62205. BABYLON.MirrorTexture = MirrorTexture;
  62206. })(BABYLON || (BABYLON = {}));
  62207. //# sourceMappingURL=babylon.mirrorTexture.js.map
  62208. "use strict";
  62209. var BABYLON;
  62210. (function (BABYLON) {
  62211. /**
  62212. * Creates a refraction texture used by refraction channel of the standard material.
  62213. * @param name the texture name
  62214. * @param size size of the underlying texture
  62215. * @param scene root scene
  62216. */
  62217. var RefractionTexture = /** @class */ (function (_super) {
  62218. __extends(RefractionTexture, _super);
  62219. function RefractionTexture(name, size, scene, generateMipMaps) {
  62220. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  62221. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  62222. _this.depth = 2.0;
  62223. _this.onBeforeRenderObservable.add(function () {
  62224. scene.clipPlane = _this.refractionPlane;
  62225. });
  62226. _this.onAfterRenderObservable.add(function () {
  62227. delete scene.clipPlane;
  62228. });
  62229. return _this;
  62230. }
  62231. RefractionTexture.prototype.clone = function () {
  62232. var scene = this.getScene();
  62233. if (!scene) {
  62234. return this;
  62235. }
  62236. var textureSize = this.getSize();
  62237. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  62238. // Base texture
  62239. newTexture.hasAlpha = this.hasAlpha;
  62240. newTexture.level = this.level;
  62241. // Refraction Texture
  62242. newTexture.refractionPlane = this.refractionPlane.clone();
  62243. if (this.renderList) {
  62244. newTexture.renderList = this.renderList.slice(0);
  62245. }
  62246. newTexture.depth = this.depth;
  62247. return newTexture;
  62248. };
  62249. RefractionTexture.prototype.serialize = function () {
  62250. if (!this.name) {
  62251. return null;
  62252. }
  62253. var serializationObject = _super.prototype.serialize.call(this);
  62254. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  62255. serializationObject.depth = this.depth;
  62256. return serializationObject;
  62257. };
  62258. return RefractionTexture;
  62259. }(BABYLON.RenderTargetTexture));
  62260. BABYLON.RefractionTexture = RefractionTexture;
  62261. })(BABYLON || (BABYLON = {}));
  62262. //# sourceMappingURL=babylon.refractionTexture.js.map
  62263. "use strict";
  62264. var BABYLON;
  62265. (function (BABYLON) {
  62266. /**
  62267. * A class extending {BABYLON.Texture} allowing drawing on a texture
  62268. * @see http://doc.babylonjs.com/how_to/dynamictexture
  62269. */
  62270. var DynamicTexture = /** @class */ (function (_super) {
  62271. __extends(DynamicTexture, _super);
  62272. /**
  62273. * Creates a {BABYLON.DynamicTexture}
  62274. * @param name defines the name of the texture
  62275. * @param options provides 3 alternatives for width and height of texture, a canvas, object with width and height properties, number for both width and height
  62276. * @param scene defines the scene where you want the texture
  62277. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  62278. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  62279. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  62280. */
  62281. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  62282. if (scene === void 0) { scene = null; }
  62283. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  62284. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  62285. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  62286. _this.name = name;
  62287. _this._engine = _this.getScene().getEngine();
  62288. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62289. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62290. _this._generateMipMaps = generateMipMaps;
  62291. if (options.getContext) {
  62292. _this._canvas = options;
  62293. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  62294. }
  62295. else {
  62296. _this._canvas = document.createElement("canvas");
  62297. if (options.width) {
  62298. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  62299. }
  62300. else {
  62301. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  62302. }
  62303. }
  62304. var textureSize = _this.getSize();
  62305. _this._canvas.width = textureSize.width;
  62306. _this._canvas.height = textureSize.height;
  62307. _this._context = _this._canvas.getContext("2d");
  62308. return _this;
  62309. }
  62310. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  62311. /**
  62312. * Gets the current state of canRescale
  62313. */
  62314. get: function () {
  62315. return true;
  62316. },
  62317. enumerable: true,
  62318. configurable: true
  62319. });
  62320. DynamicTexture.prototype._recreate = function (textureSize) {
  62321. this._canvas.width = textureSize.width;
  62322. this._canvas.height = textureSize.height;
  62323. this.releaseInternalTexture();
  62324. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  62325. };
  62326. /**
  62327. * Scales the texture
  62328. * @param ratio the scale factor to apply to both width and height
  62329. */
  62330. DynamicTexture.prototype.scale = function (ratio) {
  62331. var textureSize = this.getSize();
  62332. textureSize.width *= ratio;
  62333. textureSize.height *= ratio;
  62334. this._recreate(textureSize);
  62335. };
  62336. /**
  62337. * Resizes the texture
  62338. * @param width the new width
  62339. * @param height the new height
  62340. */
  62341. DynamicTexture.prototype.scaleTo = function (width, height) {
  62342. var textureSize = this.getSize();
  62343. textureSize.width = width;
  62344. textureSize.height = height;
  62345. this._recreate(textureSize);
  62346. };
  62347. /**
  62348. * Gets the context of the canvas used by the texture
  62349. * @returns the canvas context of the dynamic texture
  62350. */
  62351. DynamicTexture.prototype.getContext = function () {
  62352. return this._context;
  62353. };
  62354. /**
  62355. * Clears the texture
  62356. */
  62357. DynamicTexture.prototype.clear = function () {
  62358. var size = this.getSize();
  62359. this._context.fillRect(0, 0, size.width, size.height);
  62360. };
  62361. /**
  62362. * Updates the texture
  62363. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  62364. */
  62365. DynamicTexture.prototype.update = function (invertY) {
  62366. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  62367. };
  62368. /**
  62369. * Draws text onto the texture
  62370. * @param text defines the text to be drawn
  62371. * @param x defines the placement of the text from the left
  62372. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  62373. * @param font defines the font to be used with font-style, font-size, font-name
  62374. * @param color defines the color used for the text
  62375. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  62376. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  62377. * @param update defines whether texture is immediately update (default is true)
  62378. */
  62379. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  62380. if (update === void 0) { update = true; }
  62381. var size = this.getSize();
  62382. if (clearColor) {
  62383. this._context.fillStyle = clearColor;
  62384. this._context.fillRect(0, 0, size.width, size.height);
  62385. }
  62386. this._context.font = font;
  62387. if (x === null || x === undefined) {
  62388. var textSize = this._context.measureText(text);
  62389. x = (size.width - textSize.width) / 2;
  62390. }
  62391. if (y === null || y === undefined) {
  62392. var fontSize = parseInt((font.replace(/\D/g, '')));
  62393. ;
  62394. y = (size.height / 2) + (fontSize / 3.65);
  62395. }
  62396. this._context.fillStyle = color;
  62397. this._context.fillText(text, x, y);
  62398. if (update) {
  62399. this.update(invertY);
  62400. }
  62401. };
  62402. /**
  62403. * Clones the texture
  62404. * @returns the clone of the texture.
  62405. */
  62406. DynamicTexture.prototype.clone = function () {
  62407. var scene = this.getScene();
  62408. if (!scene) {
  62409. return this;
  62410. }
  62411. var textureSize = this.getSize();
  62412. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  62413. // Base texture
  62414. newTexture.hasAlpha = this.hasAlpha;
  62415. newTexture.level = this.level;
  62416. // Dynamic Texture
  62417. newTexture.wrapU = this.wrapU;
  62418. newTexture.wrapV = this.wrapV;
  62419. return newTexture;
  62420. };
  62421. /** @ignore */
  62422. DynamicTexture.prototype._rebuild = function () {
  62423. this.update();
  62424. };
  62425. return DynamicTexture;
  62426. }(BABYLON.Texture));
  62427. BABYLON.DynamicTexture = DynamicTexture;
  62428. })(BABYLON || (BABYLON = {}));
  62429. //# sourceMappingURL=babylon.dynamicTexture.js.map
  62430. "use strict";
  62431. var BABYLON;
  62432. (function (BABYLON) {
  62433. var VideoTexture = /** @class */ (function (_super) {
  62434. __extends(VideoTexture, _super);
  62435. /**
  62436. * Creates a video texture.
  62437. * Sample : https://doc.babylonjs.com/how_to/video_texture
  62438. * @param {string | null} name optional name, will detect from video source, if not defined
  62439. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  62440. * @param {BABYLON.Scene} scene is obviously the current scene.
  62441. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  62442. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  62443. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  62444. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  62445. */
  62446. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  62447. if (generateMipMaps === void 0) { generateMipMaps = false; }
  62448. if (invertY === void 0) { invertY = false; }
  62449. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  62450. if (settings === void 0) { settings = {
  62451. autoPlay: true,
  62452. loop: true,
  62453. autoUpdateTexture: true,
  62454. }; }
  62455. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  62456. _this._createInternalTexture = function () {
  62457. if (_this._texture != null) {
  62458. return;
  62459. }
  62460. if (!_this._engine.needPOTTextures ||
  62461. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  62462. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  62463. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  62464. }
  62465. else {
  62466. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62467. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62468. _this._generateMipMaps = false;
  62469. }
  62470. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  62471. _this._texture.isReady = true;
  62472. _this._updateInternalTexture();
  62473. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  62474. _this.onLoadObservable.notifyObservers(_this);
  62475. }
  62476. };
  62477. _this.reset = function () {
  62478. if (_this._texture == null) {
  62479. return;
  62480. }
  62481. _this._texture.dispose();
  62482. _this._texture = null;
  62483. };
  62484. _this._updateInternalTexture = function (e) {
  62485. if (_this._texture == null || !_this._texture.isReady) {
  62486. return;
  62487. }
  62488. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  62489. return;
  62490. }
  62491. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  62492. };
  62493. _this._engine = _this.getScene().getEngine();
  62494. _this._generateMipMaps = generateMipMaps;
  62495. _this._samplingMode = samplingMode;
  62496. _this.autoUpdateTexture = settings.autoUpdateTexture;
  62497. _this.name = name || _this._getName(src);
  62498. _this.video = _this._getVideo(src);
  62499. if (settings.autoPlay !== undefined) {
  62500. _this.video.autoplay = settings.autoPlay;
  62501. }
  62502. if (settings.loop !== undefined) {
  62503. _this.video.loop = settings.loop;
  62504. }
  62505. _this.video.addEventListener("canplay", _this._createInternalTexture);
  62506. _this.video.addEventListener("paused", _this._updateInternalTexture);
  62507. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  62508. _this.video.addEventListener("emptied", _this.reset);
  62509. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  62510. _this._createInternalTexture();
  62511. }
  62512. return _this;
  62513. }
  62514. VideoTexture.prototype._getName = function (src) {
  62515. if (src instanceof HTMLVideoElement) {
  62516. return src.currentSrc;
  62517. }
  62518. if (typeof src === "object") {
  62519. return src.toString();
  62520. }
  62521. return src;
  62522. };
  62523. ;
  62524. VideoTexture.prototype._getVideo = function (src) {
  62525. if (src instanceof HTMLVideoElement) {
  62526. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  62527. return src;
  62528. }
  62529. var video = document.createElement("video");
  62530. if (typeof src === "string") {
  62531. BABYLON.Tools.SetCorsBehavior(src, video);
  62532. video.src = src;
  62533. }
  62534. else {
  62535. BABYLON.Tools.SetCorsBehavior(src[0], video);
  62536. src.forEach(function (url) {
  62537. var source = document.createElement("source");
  62538. source.src = url;
  62539. video.appendChild(source);
  62540. });
  62541. }
  62542. return video;
  62543. };
  62544. ;
  62545. /**
  62546. * Internal method to initiate `update`.
  62547. */
  62548. VideoTexture.prototype._rebuild = function () {
  62549. this.update();
  62550. };
  62551. /**
  62552. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  62553. */
  62554. VideoTexture.prototype.update = function () {
  62555. if (!this.autoUpdateTexture) {
  62556. // Expecting user to call `updateTexture` manually
  62557. return;
  62558. }
  62559. this.updateTexture(true);
  62560. };
  62561. /**
  62562. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  62563. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  62564. */
  62565. VideoTexture.prototype.updateTexture = function (isVisible) {
  62566. if (!isVisible) {
  62567. return;
  62568. }
  62569. if (this.video.paused) {
  62570. return;
  62571. }
  62572. this._updateInternalTexture();
  62573. };
  62574. /**
  62575. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  62576. * @param url New url.
  62577. */
  62578. VideoTexture.prototype.updateURL = function (url) {
  62579. this.video.src = url;
  62580. };
  62581. VideoTexture.prototype.dispose = function () {
  62582. _super.prototype.dispose.call(this);
  62583. this.video.removeEventListener("canplay", this._createInternalTexture);
  62584. this.video.removeEventListener("paused", this._updateInternalTexture);
  62585. this.video.removeEventListener("seeked", this._updateInternalTexture);
  62586. this.video.removeEventListener("emptied", this.reset);
  62587. this.video.pause();
  62588. };
  62589. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  62590. var video = document.createElement("video");
  62591. var constraintsDeviceId;
  62592. if (constraints && constraints.deviceId) {
  62593. constraintsDeviceId = {
  62594. exact: constraints.deviceId,
  62595. };
  62596. }
  62597. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  62598. if (navigator.mediaDevices) {
  62599. navigator.mediaDevices.getUserMedia({ video: constraints })
  62600. .then(function (stream) {
  62601. if (video.mozSrcObject !== undefined) {
  62602. // hack for Firefox < 19
  62603. video.mozSrcObject = stream;
  62604. }
  62605. else {
  62606. video.srcObject = stream;
  62607. }
  62608. var onPlaying = function () {
  62609. if (onReady) {
  62610. onReady(new VideoTexture("video", video, scene, true, true));
  62611. }
  62612. video.removeEventListener("playing", onPlaying);
  62613. };
  62614. video.addEventListener("playing", onPlaying);
  62615. video.play();
  62616. })
  62617. .catch(function (err) {
  62618. BABYLON.Tools.Error(err.name);
  62619. });
  62620. }
  62621. else {
  62622. navigator.getUserMedia =
  62623. navigator.getUserMedia ||
  62624. navigator.webkitGetUserMedia ||
  62625. navigator.mozGetUserMedia ||
  62626. navigator.msGetUserMedia;
  62627. if (navigator.getUserMedia) {
  62628. navigator.getUserMedia({
  62629. video: {
  62630. deviceId: constraintsDeviceId,
  62631. width: {
  62632. min: (constraints && constraints.minWidth) || 256,
  62633. max: (constraints && constraints.maxWidth) || 640,
  62634. },
  62635. height: {
  62636. min: (constraints && constraints.minHeight) || 256,
  62637. max: (constraints && constraints.maxHeight) || 480,
  62638. },
  62639. },
  62640. }, function (stream) {
  62641. if (video.mozSrcObject !== undefined) {
  62642. // hack for Firefox < 19
  62643. video.mozSrcObject = stream;
  62644. }
  62645. else {
  62646. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  62647. }
  62648. video.play();
  62649. if (onReady) {
  62650. onReady(new VideoTexture("video", video, scene, true, true));
  62651. }
  62652. }, function (e) {
  62653. BABYLON.Tools.Error(e.name);
  62654. });
  62655. }
  62656. }
  62657. };
  62658. return VideoTexture;
  62659. }(BABYLON.Texture));
  62660. BABYLON.VideoTexture = VideoTexture;
  62661. })(BABYLON || (BABYLON = {}));
  62662. //# sourceMappingURL=babylon.videoTexture.js.map
  62663. "use strict";
  62664. var BABYLON;
  62665. (function (BABYLON) {
  62666. var RawTexture = /** @class */ (function (_super) {
  62667. __extends(RawTexture, _super);
  62668. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  62669. if (generateMipMaps === void 0) { generateMipMaps = true; }
  62670. if (invertY === void 0) { invertY = false; }
  62671. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  62672. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62673. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  62674. _this.format = format;
  62675. _this._engine = scene.getEngine();
  62676. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  62677. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62678. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62679. return _this;
  62680. }
  62681. RawTexture.prototype.update = function (data) {
  62682. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  62683. };
  62684. // Statics
  62685. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  62686. if (generateMipMaps === void 0) { generateMipMaps = true; }
  62687. if (invertY === void 0) { invertY = false; }
  62688. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  62689. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  62690. };
  62691. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  62692. if (generateMipMaps === void 0) { generateMipMaps = true; }
  62693. if (invertY === void 0) { invertY = false; }
  62694. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  62695. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  62696. };
  62697. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  62698. if (generateMipMaps === void 0) { generateMipMaps = true; }
  62699. if (invertY === void 0) { invertY = false; }
  62700. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  62701. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  62702. };
  62703. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  62704. if (generateMipMaps === void 0) { generateMipMaps = true; }
  62705. if (invertY === void 0) { invertY = false; }
  62706. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  62707. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62708. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  62709. };
  62710. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  62711. if (generateMipMaps === void 0) { generateMipMaps = true; }
  62712. if (invertY === void 0) { invertY = false; }
  62713. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  62714. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62715. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  62716. };
  62717. return RawTexture;
  62718. }(BABYLON.Texture));
  62719. BABYLON.RawTexture = RawTexture;
  62720. })(BABYLON || (BABYLON = {}));
  62721. //# sourceMappingURL=babylon.rawTexture.js.map
  62722. "use strict";
  62723. var BABYLON;
  62724. (function (BABYLON) {
  62725. /**
  62726. * PostProcess can be used to apply a shader to a texture after it has been rendered
  62727. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  62728. */
  62729. var PostProcess = /** @class */ (function () {
  62730. /**
  62731. * Creates a new instance PostProcess
  62732. * @param name The name of the PostProcess.
  62733. * @param fragmentUrl The url of the fragment shader to be used.
  62734. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  62735. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  62736. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  62737. * @param camera The camera to apply the render pass to.
  62738. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  62739. * @param engine The engine which the post process will be applied. (default: current engine)
  62740. * @param reusable If the post process can be reused on the same frame. (default: false)
  62741. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  62742. * @param textureType Type of textures used when performing the post process. (default: 0)
  62743. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  62744. * @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
  62745. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  62746. */
  62747. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  62748. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  62749. if (defines === void 0) { defines = null; }
  62750. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62751. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  62752. if (blockCompilation === void 0) { blockCompilation = false; }
  62753. this.name = name;
  62754. /**
  62755. * Width of the texture to apply the post process on
  62756. */
  62757. this.width = -1;
  62758. /**
  62759. * Height of the texture to apply the post process on
  62760. */
  62761. this.height = -1;
  62762. /**
  62763. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  62764. */
  62765. this._outputTexture = null;
  62766. /**
  62767. * If the buffer needs to be cleared before applying the post process. (default: true)
  62768. * Should be set to false if shader will overwrite all previous pixels.
  62769. */
  62770. this.autoClear = true;
  62771. /**
  62772. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  62773. */
  62774. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  62775. /**
  62776. * Animations to be used for the post processing
  62777. */
  62778. this.animations = new Array();
  62779. /**
  62780. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  62781. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  62782. */
  62783. this.enablePixelPerfectMode = false;
  62784. /**
  62785. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  62786. */
  62787. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  62788. /**
  62789. * Force textures to be a power of two (default: false)
  62790. */
  62791. this.alwaysForcePOT = false;
  62792. /**
  62793. * Number of sample textures (default: 1)
  62794. */
  62795. this.samples = 1;
  62796. /**
  62797. * Modify the scale of the post process to be the same as the viewport (default: false)
  62798. */
  62799. this.adaptScaleToCurrentViewport = false;
  62800. this._reusable = false;
  62801. /**
  62802. * Smart array of input and output textures for the post process.
  62803. */
  62804. this._textures = new BABYLON.SmartArray(2);
  62805. /**
  62806. * The index in _textures that corresponds to the output texture.
  62807. */
  62808. this._currentRenderTextureInd = 0;
  62809. this._scaleRatio = new BABYLON.Vector2(1, 1);
  62810. this._texelSize = BABYLON.Vector2.Zero();
  62811. // Events
  62812. /**
  62813. * An event triggered when the postprocess is activated.
  62814. */
  62815. this.onActivateObservable = new BABYLON.Observable();
  62816. /**
  62817. * An event triggered when the postprocess changes its size.
  62818. */
  62819. this.onSizeChangedObservable = new BABYLON.Observable();
  62820. /**
  62821. * An event triggered when the postprocess applies its effect.
  62822. */
  62823. this.onApplyObservable = new BABYLON.Observable();
  62824. /**
  62825. * An event triggered before rendering the postprocess
  62826. */
  62827. this.onBeforeRenderObservable = new BABYLON.Observable();
  62828. /**
  62829. * An event triggered after rendering the postprocess
  62830. */
  62831. this.onAfterRenderObservable = new BABYLON.Observable();
  62832. if (camera != null) {
  62833. this._camera = camera;
  62834. this._scene = camera.getScene();
  62835. camera.attachPostProcess(this);
  62836. this._engine = this._scene.getEngine();
  62837. this._scene.postProcesses.push(this);
  62838. }
  62839. else if (engine) {
  62840. this._engine = engine;
  62841. this._engine.postProcesses.push(this);
  62842. }
  62843. this._options = options;
  62844. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  62845. this._reusable = reusable || false;
  62846. this._textureType = textureType;
  62847. this._samplers = samplers || [];
  62848. this._samplers.push("textureSampler");
  62849. this._fragmentUrl = fragmentUrl;
  62850. this._vertexUrl = vertexUrl;
  62851. this._parameters = parameters || [];
  62852. this._parameters.push("scale");
  62853. this._indexParameters = indexParameters;
  62854. if (!blockCompilation) {
  62855. this.updateEffect(defines);
  62856. }
  62857. }
  62858. Object.defineProperty(PostProcess.prototype, "onActivate", {
  62859. /**
  62860. * A function that is added to the onActivateObservable
  62861. */
  62862. set: function (callback) {
  62863. if (this._onActivateObserver) {
  62864. this.onActivateObservable.remove(this._onActivateObserver);
  62865. }
  62866. if (callback) {
  62867. this._onActivateObserver = this.onActivateObservable.add(callback);
  62868. }
  62869. },
  62870. enumerable: true,
  62871. configurable: true
  62872. });
  62873. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  62874. /**
  62875. * A function that is added to the onSizeChangedObservable
  62876. */
  62877. set: function (callback) {
  62878. if (this._onSizeChangedObserver) {
  62879. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  62880. }
  62881. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  62882. },
  62883. enumerable: true,
  62884. configurable: true
  62885. });
  62886. Object.defineProperty(PostProcess.prototype, "onApply", {
  62887. /**
  62888. * A function that is added to the onApplyObservable
  62889. */
  62890. set: function (callback) {
  62891. if (this._onApplyObserver) {
  62892. this.onApplyObservable.remove(this._onApplyObserver);
  62893. }
  62894. this._onApplyObserver = this.onApplyObservable.add(callback);
  62895. },
  62896. enumerable: true,
  62897. configurable: true
  62898. });
  62899. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  62900. /**
  62901. * A function that is added to the onBeforeRenderObservable
  62902. */
  62903. set: function (callback) {
  62904. if (this._onBeforeRenderObserver) {
  62905. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  62906. }
  62907. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  62908. },
  62909. enumerable: true,
  62910. configurable: true
  62911. });
  62912. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  62913. /**
  62914. * A function that is added to the onAfterRenderObservable
  62915. */
  62916. set: function (callback) {
  62917. if (this._onAfterRenderObserver) {
  62918. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  62919. }
  62920. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  62921. },
  62922. enumerable: true,
  62923. configurable: true
  62924. });
  62925. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  62926. /**
  62927. * 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
  62928. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  62929. */
  62930. get: function () {
  62931. return this._textures.data[this._currentRenderTextureInd];
  62932. },
  62933. set: function (value) {
  62934. this._forcedOutputTexture = value;
  62935. },
  62936. enumerable: true,
  62937. configurable: true
  62938. });
  62939. /**
  62940. * Gets the camera which post process is applied to.
  62941. * @returns The camera the post process is applied to.
  62942. */
  62943. PostProcess.prototype.getCamera = function () {
  62944. return this._camera;
  62945. };
  62946. Object.defineProperty(PostProcess.prototype, "texelSize", {
  62947. /**
  62948. * Gets the texel size of the postprocess.
  62949. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  62950. */
  62951. get: function () {
  62952. if (this._shareOutputWithPostProcess) {
  62953. return this._shareOutputWithPostProcess.texelSize;
  62954. }
  62955. if (this._forcedOutputTexture) {
  62956. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  62957. }
  62958. return this._texelSize;
  62959. },
  62960. enumerable: true,
  62961. configurable: true
  62962. });
  62963. /**
  62964. * Gets the engine which this post process belongs to.
  62965. * @returns The engine the post process was enabled with.
  62966. */
  62967. PostProcess.prototype.getEngine = function () {
  62968. return this._engine;
  62969. };
  62970. /**
  62971. * The effect that is created when initializing the post process.
  62972. * @returns The created effect corrisponding the the postprocess.
  62973. */
  62974. PostProcess.prototype.getEffect = function () {
  62975. return this._effect;
  62976. };
  62977. /**
  62978. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  62979. * @param postProcess The post process to share the output with.
  62980. * @returns This post process.
  62981. */
  62982. PostProcess.prototype.shareOutputWith = function (postProcess) {
  62983. this._disposeTextures();
  62984. this._shareOutputWithPostProcess = postProcess;
  62985. return this;
  62986. };
  62987. /**
  62988. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  62989. * This should be called if the post process that shares output with this post process is disabled/disposed.
  62990. */
  62991. PostProcess.prototype.useOwnOutput = function () {
  62992. if (this._textures.length == 0) {
  62993. this._textures = new BABYLON.SmartArray(2);
  62994. }
  62995. this._shareOutputWithPostProcess = null;
  62996. };
  62997. /**
  62998. * Updates the effect with the current post process compile time values and recompiles the shader.
  62999. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  63000. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  63001. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  63002. * @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
  63003. * @param onCompiled Called when the shader has been compiled.
  63004. * @param onError Called if there is an error when compiling a shader.
  63005. */
  63006. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  63007. if (defines === void 0) { defines = null; }
  63008. if (uniforms === void 0) { uniforms = null; }
  63009. if (samplers === void 0) { samplers = null; }
  63010. 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);
  63011. };
  63012. /**
  63013. * The post process is reusable if it can be used multiple times within one frame.
  63014. * @returns If the post process is reusable
  63015. */
  63016. PostProcess.prototype.isReusable = function () {
  63017. return this._reusable;
  63018. };
  63019. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  63020. PostProcess.prototype.markTextureDirty = function () {
  63021. this.width = -1;
  63022. };
  63023. /**
  63024. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  63025. * 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.
  63026. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  63027. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  63028. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  63029. * @returns The target texture that was bound to be written to.
  63030. */
  63031. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  63032. var _this = this;
  63033. if (sourceTexture === void 0) { sourceTexture = null; }
  63034. camera = camera || this._camera;
  63035. var scene = camera.getScene();
  63036. var engine = scene.getEngine();
  63037. var maxSize = engine.getCaps().maxTextureSize;
  63038. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  63039. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  63040. // 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
  63041. var webVRCamera = camera.parent;
  63042. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  63043. requiredWidth /= 2;
  63044. }
  63045. var desiredWidth = (this._options.width || requiredWidth);
  63046. var desiredHeight = this._options.height || requiredHeight;
  63047. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  63048. if (this.adaptScaleToCurrentViewport) {
  63049. var currentViewport = engine.currentViewport;
  63050. if (currentViewport) {
  63051. desiredWidth *= currentViewport.width;
  63052. desiredHeight *= currentViewport.height;
  63053. }
  63054. }
  63055. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  63056. if (!this._options.width) {
  63057. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  63058. }
  63059. if (!this._options.height) {
  63060. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  63061. }
  63062. }
  63063. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  63064. if (this._textures.length > 0) {
  63065. for (var i = 0; i < this._textures.length; i++) {
  63066. this._engine._releaseTexture(this._textures.data[i]);
  63067. }
  63068. this._textures.reset();
  63069. }
  63070. this.width = desiredWidth;
  63071. this.height = desiredHeight;
  63072. var textureSize = { width: this.width, height: this.height };
  63073. var textureOptions = {
  63074. generateMipMaps: false,
  63075. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  63076. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  63077. samplingMode: this.renderTargetSamplingMode,
  63078. type: this._textureType
  63079. };
  63080. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  63081. if (this._reusable) {
  63082. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  63083. }
  63084. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  63085. this.onSizeChangedObservable.notifyObservers(this);
  63086. }
  63087. this._textures.forEach(function (texture) {
  63088. if (texture.samples !== _this.samples) {
  63089. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  63090. }
  63091. });
  63092. }
  63093. var target;
  63094. if (this._shareOutputWithPostProcess) {
  63095. target = this._shareOutputWithPostProcess.inputTexture;
  63096. }
  63097. else if (this._forcedOutputTexture) {
  63098. target = this._forcedOutputTexture;
  63099. this.width = this._forcedOutputTexture.width;
  63100. this.height = this._forcedOutputTexture.height;
  63101. }
  63102. else {
  63103. target = this.inputTexture;
  63104. }
  63105. // Bind the input of this post process to be used as the output of the previous post process.
  63106. if (this.enablePixelPerfectMode) {
  63107. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  63108. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  63109. }
  63110. else {
  63111. this._scaleRatio.copyFromFloats(1, 1);
  63112. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  63113. }
  63114. this.onActivateObservable.notifyObservers(camera);
  63115. // Clear
  63116. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  63117. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  63118. }
  63119. if (this._reusable) {
  63120. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  63121. }
  63122. return target;
  63123. };
  63124. Object.defineProperty(PostProcess.prototype, "isSupported", {
  63125. /**
  63126. * If the post process is supported.
  63127. */
  63128. get: function () {
  63129. return this._effect.isSupported;
  63130. },
  63131. enumerable: true,
  63132. configurable: true
  63133. });
  63134. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  63135. /**
  63136. * The aspect ratio of the output texture.
  63137. */
  63138. get: function () {
  63139. if (this._shareOutputWithPostProcess) {
  63140. return this._shareOutputWithPostProcess.aspectRatio;
  63141. }
  63142. if (this._forcedOutputTexture) {
  63143. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  63144. }
  63145. return this.width / this.height;
  63146. },
  63147. enumerable: true,
  63148. configurable: true
  63149. });
  63150. /**
  63151. * Get a value indicating if the post-process is ready to be used
  63152. * @returns true if the post-process is ready (shader is compiled)
  63153. */
  63154. PostProcess.prototype.isReady = function () {
  63155. return this._effect && this._effect.isReady();
  63156. };
  63157. /**
  63158. * Binds all textures and uniforms to the shader, this will be run on every pass.
  63159. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  63160. */
  63161. PostProcess.prototype.apply = function () {
  63162. // Check
  63163. if (!this._effect || !this._effect.isReady())
  63164. return null;
  63165. // States
  63166. this._engine.enableEffect(this._effect);
  63167. this._engine.setState(false);
  63168. this._engine.setDepthBuffer(false);
  63169. this._engine.setDepthWrite(false);
  63170. // Alpha
  63171. this._engine.setAlphaMode(this.alphaMode);
  63172. if (this.alphaConstants) {
  63173. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  63174. }
  63175. // Bind the output texture of the preivous post process as the input to this post process.
  63176. var source;
  63177. if (this._shareOutputWithPostProcess) {
  63178. source = this._shareOutputWithPostProcess.inputTexture;
  63179. }
  63180. else if (this._forcedOutputTexture) {
  63181. source = this._forcedOutputTexture;
  63182. }
  63183. else {
  63184. source = this.inputTexture;
  63185. }
  63186. this._effect._bindTexture("textureSampler", source);
  63187. // Parameters
  63188. this._effect.setVector2("scale", this._scaleRatio);
  63189. this.onApplyObservable.notifyObservers(this._effect);
  63190. return this._effect;
  63191. };
  63192. PostProcess.prototype._disposeTextures = function () {
  63193. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  63194. return;
  63195. }
  63196. if (this._textures.length > 0) {
  63197. for (var i = 0; i < this._textures.length; i++) {
  63198. this._engine._releaseTexture(this._textures.data[i]);
  63199. }
  63200. }
  63201. this._textures.dispose();
  63202. };
  63203. /**
  63204. * Disposes the post process.
  63205. * @param camera The camera to dispose the post process on.
  63206. */
  63207. PostProcess.prototype.dispose = function (camera) {
  63208. camera = camera || this._camera;
  63209. this._disposeTextures();
  63210. if (this._scene) {
  63211. var index_1 = this._scene.postProcesses.indexOf(this);
  63212. if (index_1 !== -1) {
  63213. this._scene.postProcesses.splice(index_1, 1);
  63214. }
  63215. }
  63216. else {
  63217. var index_2 = this._engine.postProcesses.indexOf(this);
  63218. if (index_2 !== -1) {
  63219. this._engine.postProcesses.splice(index_2, 1);
  63220. }
  63221. }
  63222. if (!camera) {
  63223. return;
  63224. }
  63225. camera.detachPostProcess(this);
  63226. var index = camera._postProcesses.indexOf(this);
  63227. if (index === 0 && camera._postProcesses.length > 0) {
  63228. var firstPostProcess = this._camera._getFirstPostProcess();
  63229. if (firstPostProcess) {
  63230. firstPostProcess.markTextureDirty();
  63231. }
  63232. }
  63233. this.onActivateObservable.clear();
  63234. this.onAfterRenderObservable.clear();
  63235. this.onApplyObservable.clear();
  63236. this.onBeforeRenderObservable.clear();
  63237. this.onSizeChangedObservable.clear();
  63238. };
  63239. return PostProcess;
  63240. }());
  63241. BABYLON.PostProcess = PostProcess;
  63242. })(BABYLON || (BABYLON = {}));
  63243. //# sourceMappingURL=babylon.postProcess.js.map
  63244. "use strict";
  63245. var BABYLON;
  63246. (function (BABYLON) {
  63247. var PassPostProcess = /** @class */ (function (_super) {
  63248. __extends(PassPostProcess, _super);
  63249. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  63250. if (camera === void 0) { camera = null; }
  63251. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63252. if (blockCompilation === void 0) { blockCompilation = false; }
  63253. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  63254. }
  63255. return PassPostProcess;
  63256. }(BABYLON.PostProcess));
  63257. BABYLON.PassPostProcess = PassPostProcess;
  63258. })(BABYLON || (BABYLON = {}));
  63259. //# sourceMappingURL=babylon.passPostProcess.js.map
  63260. "use strict";
  63261. var __assign = (this && this.__assign) || Object.assign || function(t) {
  63262. for (var s, i = 1, n = arguments.length; i < n; i++) {
  63263. s = arguments[i];
  63264. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  63265. t[p] = s[p];
  63266. }
  63267. return t;
  63268. };
  63269. var BABYLON;
  63270. (function (BABYLON) {
  63271. /**
  63272. * Default implementation IShadowGenerator.
  63273. * This is the main object responsible of generating shadows in the framework.
  63274. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  63275. */
  63276. var ShadowGenerator = /** @class */ (function () {
  63277. /**
  63278. * Creates a ShadowGenerator object.
  63279. * A ShadowGenerator is the required tool to use the shadows.
  63280. * Each light casting shadows needs to use its own ShadowGenerator.
  63281. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  63282. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  63283. * @param light The light object generating the shadows.
  63284. * @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.
  63285. */
  63286. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  63287. this._bias = 0.00005;
  63288. this._normalBias = 0;
  63289. this._blurBoxOffset = 1;
  63290. this._blurScale = 2;
  63291. this._blurKernel = 1;
  63292. this._useKernelBlur = false;
  63293. this._filter = ShadowGenerator.FILTER_NONE;
  63294. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  63295. this._contactHardeningLightSizeUVRatio = 0.1;
  63296. this._darkness = 0;
  63297. this._transparencyShadow = false;
  63298. /**
  63299. * Controls the extent to which the shadows fade out at the edge of the frustum
  63300. * Used only by directionals and spots
  63301. */
  63302. this.frustumEdgeFalloff = 0;
  63303. /**
  63304. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  63305. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  63306. * It might on the other hand introduce peter panning.
  63307. */
  63308. this.forceBackFacesOnly = false;
  63309. this._lightDirection = BABYLON.Vector3.Zero();
  63310. this._viewMatrix = BABYLON.Matrix.Zero();
  63311. this._projectionMatrix = BABYLON.Matrix.Zero();
  63312. this._transformMatrix = BABYLON.Matrix.Zero();
  63313. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  63314. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  63315. this._currentFaceIndex = 0;
  63316. this._currentFaceIndexCache = 0;
  63317. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  63318. this._mapSize = mapSize;
  63319. this._light = light;
  63320. this._scene = light.getScene();
  63321. light._shadowGenerator = this;
  63322. // Texture type fallback from float to int if not supported.
  63323. var caps = this._scene.getEngine().getCaps();
  63324. if (!useFullFloatFirst) {
  63325. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  63326. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  63327. }
  63328. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  63329. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  63330. }
  63331. else {
  63332. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  63333. }
  63334. }
  63335. else {
  63336. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  63337. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  63338. }
  63339. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  63340. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  63341. }
  63342. else {
  63343. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  63344. }
  63345. }
  63346. this._initializeGenerator();
  63347. this._applyFilterValues();
  63348. }
  63349. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  63350. /**
  63351. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  63352. */
  63353. get: function () {
  63354. return this._bias;
  63355. },
  63356. /**
  63357. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  63358. */
  63359. set: function (bias) {
  63360. this._bias = bias;
  63361. },
  63362. enumerable: true,
  63363. configurable: true
  63364. });
  63365. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  63366. /**
  63367. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  63368. */
  63369. get: function () {
  63370. return this._normalBias;
  63371. },
  63372. /**
  63373. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  63374. */
  63375. set: function (normalBias) {
  63376. this._normalBias = normalBias;
  63377. },
  63378. enumerable: true,
  63379. configurable: true
  63380. });
  63381. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  63382. /**
  63383. * Gets the blur box offset: offset applied during the blur pass.
  63384. * Only usefull if useKernelBlur = false
  63385. */
  63386. get: function () {
  63387. return this._blurBoxOffset;
  63388. },
  63389. /**
  63390. * Sets the blur box offset: offset applied during the blur pass.
  63391. * Only usefull if useKernelBlur = false
  63392. */
  63393. set: function (value) {
  63394. if (this._blurBoxOffset === value) {
  63395. return;
  63396. }
  63397. this._blurBoxOffset = value;
  63398. this._disposeBlurPostProcesses();
  63399. },
  63400. enumerable: true,
  63401. configurable: true
  63402. });
  63403. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  63404. /**
  63405. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  63406. * 2 means half of the size.
  63407. */
  63408. get: function () {
  63409. return this._blurScale;
  63410. },
  63411. /**
  63412. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  63413. * 2 means half of the size.
  63414. */
  63415. set: function (value) {
  63416. if (this._blurScale === value) {
  63417. return;
  63418. }
  63419. this._blurScale = value;
  63420. this._disposeBlurPostProcesses();
  63421. },
  63422. enumerable: true,
  63423. configurable: true
  63424. });
  63425. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  63426. /**
  63427. * Gets the blur kernel: kernel size of the blur pass.
  63428. * Only usefull if useKernelBlur = true
  63429. */
  63430. get: function () {
  63431. return this._blurKernel;
  63432. },
  63433. /**
  63434. * Sets the blur kernel: kernel size of the blur pass.
  63435. * Only usefull if useKernelBlur = true
  63436. */
  63437. set: function (value) {
  63438. if (this._blurKernel === value) {
  63439. return;
  63440. }
  63441. this._blurKernel = value;
  63442. this._disposeBlurPostProcesses();
  63443. },
  63444. enumerable: true,
  63445. configurable: true
  63446. });
  63447. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  63448. /**
  63449. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  63450. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  63451. */
  63452. get: function () {
  63453. return this._useKernelBlur;
  63454. },
  63455. /**
  63456. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  63457. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  63458. */
  63459. set: function (value) {
  63460. if (this._useKernelBlur === value) {
  63461. return;
  63462. }
  63463. this._useKernelBlur = value;
  63464. this._disposeBlurPostProcesses();
  63465. },
  63466. enumerable: true,
  63467. configurable: true
  63468. });
  63469. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  63470. /**
  63471. * Gets the depth scale used in ESM mode.
  63472. */
  63473. get: function () {
  63474. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  63475. },
  63476. /**
  63477. * Sets the depth scale used in ESM mode.
  63478. * This can override the scale stored on the light.
  63479. */
  63480. set: function (value) {
  63481. this._depthScale = value;
  63482. },
  63483. enumerable: true,
  63484. configurable: true
  63485. });
  63486. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  63487. /**
  63488. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  63489. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  63490. */
  63491. get: function () {
  63492. return this._filter;
  63493. },
  63494. /**
  63495. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  63496. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  63497. */
  63498. set: function (value) {
  63499. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  63500. if (this._light.needCube()) {
  63501. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  63502. this.useExponentialShadowMap = true;
  63503. return;
  63504. }
  63505. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  63506. this.useCloseExponentialShadowMap = true;
  63507. return;
  63508. }
  63509. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  63510. this.usePoissonSampling = true;
  63511. return;
  63512. }
  63513. }
  63514. // Weblg1 fallback for PCF.
  63515. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  63516. if (this._scene.getEngine().webGLVersion === 1) {
  63517. this.usePoissonSampling = true;
  63518. return;
  63519. }
  63520. }
  63521. if (this._filter === value) {
  63522. return;
  63523. }
  63524. this._filter = value;
  63525. this._disposeBlurPostProcesses();
  63526. this._applyFilterValues();
  63527. this._light._markMeshesAsLightDirty();
  63528. },
  63529. enumerable: true,
  63530. configurable: true
  63531. });
  63532. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  63533. /**
  63534. * Gets if the current filter is set to Poisson Sampling.
  63535. */
  63536. get: function () {
  63537. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  63538. },
  63539. /**
  63540. * Sets the current filter to Poisson Sampling.
  63541. */
  63542. set: function (value) {
  63543. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  63544. return;
  63545. }
  63546. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  63547. },
  63548. enumerable: true,
  63549. configurable: true
  63550. });
  63551. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  63552. /**
  63553. * Gets if the current filter is set to VSM.
  63554. * DEPRECATED. Should use useExponentialShadowMap instead.
  63555. */
  63556. get: function () {
  63557. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  63558. return this.useExponentialShadowMap;
  63559. },
  63560. /**
  63561. * Sets the current filter is to VSM.
  63562. * DEPRECATED. Should use useExponentialShadowMap instead.
  63563. */
  63564. set: function (value) {
  63565. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  63566. this.useExponentialShadowMap = value;
  63567. },
  63568. enumerable: true,
  63569. configurable: true
  63570. });
  63571. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  63572. /**
  63573. * Gets if the current filter is set to blurred VSM.
  63574. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  63575. */
  63576. get: function () {
  63577. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  63578. return this.useBlurExponentialShadowMap;
  63579. },
  63580. /**
  63581. * Sets the current filter is to blurred VSM.
  63582. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  63583. */
  63584. set: function (value) {
  63585. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  63586. this.useBlurExponentialShadowMap = value;
  63587. },
  63588. enumerable: true,
  63589. configurable: true
  63590. });
  63591. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  63592. /**
  63593. * Gets if the current filter is set to ESM.
  63594. */
  63595. get: function () {
  63596. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  63597. },
  63598. /**
  63599. * Sets the current filter is to ESM.
  63600. */
  63601. set: function (value) {
  63602. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  63603. return;
  63604. }
  63605. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  63606. },
  63607. enumerable: true,
  63608. configurable: true
  63609. });
  63610. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  63611. /**
  63612. * Gets if the current filter is set to filtered ESM.
  63613. */
  63614. get: function () {
  63615. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  63616. },
  63617. /**
  63618. * Gets if the current filter is set to filtered ESM.
  63619. */
  63620. set: function (value) {
  63621. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  63622. return;
  63623. }
  63624. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  63625. },
  63626. enumerable: true,
  63627. configurable: true
  63628. });
  63629. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  63630. /**
  63631. * Gets if the current filter is set to "close ESM" (using the inverse of the
  63632. * exponential to prevent steep falloff artifacts).
  63633. */
  63634. get: function () {
  63635. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  63636. },
  63637. /**
  63638. * Sets the current filter to "close ESM" (using the inverse of the
  63639. * exponential to prevent steep falloff artifacts).
  63640. */
  63641. set: function (value) {
  63642. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  63643. return;
  63644. }
  63645. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  63646. },
  63647. enumerable: true,
  63648. configurable: true
  63649. });
  63650. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  63651. /**
  63652. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  63653. * exponential to prevent steep falloff artifacts).
  63654. */
  63655. get: function () {
  63656. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  63657. },
  63658. /**
  63659. * Sets the current filter to filtered "close ESM" (using the inverse of the
  63660. * exponential to prevent steep falloff artifacts).
  63661. */
  63662. set: function (value) {
  63663. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  63664. return;
  63665. }
  63666. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  63667. },
  63668. enumerable: true,
  63669. configurable: true
  63670. });
  63671. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  63672. /**
  63673. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  63674. */
  63675. get: function () {
  63676. return this.filter === ShadowGenerator.FILTER_PCF;
  63677. },
  63678. /**
  63679. * Sets the current filter to "PCF" (percentage closer filtering).
  63680. */
  63681. set: function (value) {
  63682. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  63683. return;
  63684. }
  63685. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  63686. },
  63687. enumerable: true,
  63688. configurable: true
  63689. });
  63690. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  63691. /**
  63692. * Gets the PCF or PCSS Quality.
  63693. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  63694. */
  63695. get: function () {
  63696. return this._filteringQuality;
  63697. },
  63698. /**
  63699. * Sets the PCF or PCSS Quality.
  63700. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  63701. */
  63702. set: function (filteringQuality) {
  63703. this._filteringQuality = filteringQuality;
  63704. },
  63705. enumerable: true,
  63706. configurable: true
  63707. });
  63708. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  63709. /**
  63710. * Gets if the current filter is set to "PCSS" (contact hardening).
  63711. */
  63712. get: function () {
  63713. return this.filter === ShadowGenerator.FILTER_PCSS;
  63714. },
  63715. /**
  63716. * Sets the current filter to "PCSS" (contact hardening).
  63717. */
  63718. set: function (value) {
  63719. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  63720. return;
  63721. }
  63722. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  63723. },
  63724. enumerable: true,
  63725. configurable: true
  63726. });
  63727. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  63728. /**
  63729. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  63730. * Using a ratio helps keeping shape stability independently of the map size.
  63731. *
  63732. * It does not account for the light projection as it was having too much
  63733. * instability during the light setup or during light position changes.
  63734. *
  63735. * Only valid if useContactHardeningShadow is true.
  63736. */
  63737. get: function () {
  63738. return this._contactHardeningLightSizeUVRatio;
  63739. },
  63740. /**
  63741. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  63742. * Using a ratio helps keeping shape stability independently of the map size.
  63743. *
  63744. * It does not account for the light projection as it was having too much
  63745. * instability during the light setup or during light position changes.
  63746. *
  63747. * Only valid if useContactHardeningShadow is true.
  63748. */
  63749. set: function (contactHardeningLightSizeUVRatio) {
  63750. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  63751. },
  63752. enumerable: true,
  63753. configurable: true
  63754. });
  63755. /**
  63756. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  63757. * 0 means strongest and 1 would means no shadow.
  63758. * @returns the darkness.
  63759. */
  63760. ShadowGenerator.prototype.getDarkness = function () {
  63761. return this._darkness;
  63762. };
  63763. /**
  63764. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  63765. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  63766. * @returns the shadow generator allowing fluent coding.
  63767. */
  63768. ShadowGenerator.prototype.setDarkness = function (darkness) {
  63769. if (darkness >= 1.0)
  63770. this._darkness = 1.0;
  63771. else if (darkness <= 0.0)
  63772. this._darkness = 0.0;
  63773. else
  63774. this._darkness = darkness;
  63775. return this;
  63776. };
  63777. /**
  63778. * Sets the ability to have transparent shadow (boolean).
  63779. * @param transparent True if transparent else False
  63780. * @returns the shadow generator allowing fluent coding
  63781. */
  63782. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  63783. this._transparencyShadow = transparent;
  63784. return this;
  63785. };
  63786. /**
  63787. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  63788. * @returns The render target texture if present otherwise, null
  63789. */
  63790. ShadowGenerator.prototype.getShadowMap = function () {
  63791. return this._shadowMap;
  63792. };
  63793. /**
  63794. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  63795. * @returns The render target texture if the shadow map is present otherwise, null
  63796. */
  63797. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  63798. if (this._shadowMap2) {
  63799. return this._shadowMap2;
  63800. }
  63801. return this._shadowMap;
  63802. };
  63803. /**
  63804. * Helper function to add a mesh and its descendants to the list of shadow casters.
  63805. * @param mesh Mesh to add
  63806. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  63807. * @returns the Shadow Generator itself
  63808. */
  63809. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  63810. if (includeDescendants === void 0) { includeDescendants = true; }
  63811. if (!this._shadowMap) {
  63812. return this;
  63813. }
  63814. if (!this._shadowMap.renderList) {
  63815. this._shadowMap.renderList = [];
  63816. }
  63817. this._shadowMap.renderList.push(mesh);
  63818. if (includeDescendants) {
  63819. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  63820. }
  63821. return this;
  63822. var _a;
  63823. };
  63824. /**
  63825. * Helper function to remove a mesh and its descendants from the list of shadow casters
  63826. * @param mesh Mesh to remove
  63827. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  63828. * @returns the Shadow Generator itself
  63829. */
  63830. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  63831. if (includeDescendants === void 0) { includeDescendants = true; }
  63832. if (!this._shadowMap || !this._shadowMap.renderList) {
  63833. return this;
  63834. }
  63835. var index = this._shadowMap.renderList.indexOf(mesh);
  63836. if (index !== -1) {
  63837. this._shadowMap.renderList.splice(index, 1);
  63838. }
  63839. if (includeDescendants) {
  63840. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  63841. var child = _a[_i];
  63842. this.removeShadowCaster(child);
  63843. }
  63844. }
  63845. return this;
  63846. };
  63847. /**
  63848. * Returns the associated light object.
  63849. * @returns the light generating the shadow
  63850. */
  63851. ShadowGenerator.prototype.getLight = function () {
  63852. return this._light;
  63853. };
  63854. ShadowGenerator.prototype._initializeGenerator = function () {
  63855. this._light._markMeshesAsLightDirty();
  63856. this._initializeShadowMap();
  63857. };
  63858. ShadowGenerator.prototype._initializeShadowMap = function () {
  63859. var _this = this;
  63860. // Render target
  63861. var engine = this._scene.getEngine();
  63862. if (engine.webGLVersion > 1) {
  63863. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  63864. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  63865. }
  63866. else {
  63867. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  63868. }
  63869. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63870. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63871. this._shadowMap.anisotropicFilteringLevel = 1;
  63872. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  63873. this._shadowMap.renderParticles = false;
  63874. this._shadowMap.ignoreCameraViewport = true;
  63875. // Record Face Index before render.
  63876. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  63877. _this._currentFaceIndex = faceIndex;
  63878. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  63879. engine.setColorWrite(false);
  63880. }
  63881. });
  63882. // Custom render function.
  63883. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  63884. // Blur if required afer render.
  63885. this._shadowMap.onAfterUnbindObservable.add(function () {
  63886. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  63887. engine.setColorWrite(true);
  63888. }
  63889. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  63890. return;
  63891. }
  63892. var shadowMap = _this.getShadowMapForRendering();
  63893. if (shadowMap) {
  63894. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  63895. }
  63896. });
  63897. // Clear according to the chosen filter.
  63898. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  63899. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  63900. this._shadowMap.onClearObservable.add(function (engine) {
  63901. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  63902. engine.clear(clearOne, false, true, false);
  63903. }
  63904. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  63905. engine.clear(clearZero, true, true, false);
  63906. }
  63907. else {
  63908. engine.clear(clearOne, true, true, false);
  63909. }
  63910. });
  63911. };
  63912. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  63913. var _this = this;
  63914. var engine = this._scene.getEngine();
  63915. var targetSize = this._mapSize / this.blurScale;
  63916. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  63917. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  63918. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63919. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63920. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  63921. }
  63922. if (this.useKernelBlur) {
  63923. 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);
  63924. this._kernelBlurXPostprocess.width = targetSize;
  63925. this._kernelBlurXPostprocess.height = targetSize;
  63926. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  63927. effect.setTexture("textureSampler", _this._shadowMap);
  63928. });
  63929. 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);
  63930. this._kernelBlurXPostprocess.autoClear = false;
  63931. this._kernelBlurYPostprocess.autoClear = false;
  63932. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  63933. this._kernelBlurXPostprocess.packedFloat = true;
  63934. this._kernelBlurYPostprocess.packedFloat = true;
  63935. }
  63936. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  63937. }
  63938. else {
  63939. 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);
  63940. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  63941. effect.setFloat2("screenSize", targetSize, targetSize);
  63942. effect.setTexture("textureSampler", _this._shadowMap);
  63943. });
  63944. this._boxBlurPostprocess.autoClear = false;
  63945. this._blurPostProcesses = [this._boxBlurPostprocess];
  63946. }
  63947. };
  63948. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  63949. var index;
  63950. var engine = this._scene.getEngine();
  63951. if (depthOnlySubMeshes.length) {
  63952. engine.setColorWrite(false);
  63953. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  63954. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  63955. }
  63956. engine.setColorWrite(true);
  63957. }
  63958. for (index = 0; index < opaqueSubMeshes.length; index++) {
  63959. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  63960. }
  63961. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  63962. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  63963. }
  63964. if (this._transparencyShadow) {
  63965. for (index = 0; index < transparentSubMeshes.length; index++) {
  63966. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  63967. }
  63968. }
  63969. };
  63970. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  63971. var _this = this;
  63972. var mesh = subMesh.getRenderingMesh();
  63973. var scene = this._scene;
  63974. var engine = scene.getEngine();
  63975. var material = subMesh.getMaterial();
  63976. if (!material) {
  63977. return;
  63978. }
  63979. // Culling
  63980. engine.setState(material.backFaceCulling);
  63981. // Managing instances
  63982. var batch = mesh._getInstancesRenderList(subMesh._id);
  63983. if (batch.mustReturn) {
  63984. return;
  63985. }
  63986. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  63987. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  63988. engine.enableEffect(this._effect);
  63989. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  63990. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  63991. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  63992. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  63993. this._effect.setVector3("lightData", this._cachedDirection);
  63994. }
  63995. else {
  63996. this._effect.setVector3("lightData", this._cachedPosition);
  63997. }
  63998. if (scene.activeCamera) {
  63999. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  64000. }
  64001. // Alpha test
  64002. if (material && material.needAlphaTesting()) {
  64003. var alphaTexture = material.getAlphaTestTexture();
  64004. if (alphaTexture) {
  64005. this._effect.setTexture("diffuseSampler", alphaTexture);
  64006. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  64007. }
  64008. }
  64009. // Bones
  64010. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  64011. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  64012. }
  64013. // Morph targets
  64014. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  64015. if (this.forceBackFacesOnly) {
  64016. engine.setState(true, 0, false, true);
  64017. }
  64018. // Draw
  64019. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  64020. if (this.forceBackFacesOnly) {
  64021. engine.setState(true, 0, false, false);
  64022. }
  64023. }
  64024. else {
  64025. // Need to reset refresh rate of the shadowMap
  64026. if (this._shadowMap) {
  64027. this._shadowMap.resetRefreshCounter();
  64028. }
  64029. }
  64030. };
  64031. ShadowGenerator.prototype._applyFilterValues = function () {
  64032. if (!this._shadowMap) {
  64033. return;
  64034. }
  64035. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  64036. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  64037. }
  64038. else {
  64039. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64040. }
  64041. };
  64042. /**
  64043. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  64044. * @param onCompiled Callback triggered at the and of the effects compilation
  64045. * @param options Sets of optional options forcing the compilation with different modes
  64046. */
  64047. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  64048. var _this = this;
  64049. var localOptions = __assign({ useInstances: false }, options);
  64050. var shadowMap = this.getShadowMap();
  64051. if (!shadowMap) {
  64052. if (onCompiled) {
  64053. onCompiled(this);
  64054. }
  64055. return;
  64056. }
  64057. var renderList = shadowMap.renderList;
  64058. if (!renderList) {
  64059. if (onCompiled) {
  64060. onCompiled(this);
  64061. }
  64062. return;
  64063. }
  64064. var subMeshes = new Array();
  64065. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  64066. var mesh = renderList_1[_i];
  64067. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  64068. }
  64069. if (subMeshes.length === 0) {
  64070. if (onCompiled) {
  64071. onCompiled(this);
  64072. }
  64073. return;
  64074. }
  64075. var currentIndex = 0;
  64076. var checkReady = function () {
  64077. if (!_this._scene || !_this._scene.getEngine()) {
  64078. return;
  64079. }
  64080. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  64081. currentIndex++;
  64082. if (currentIndex >= subMeshes.length) {
  64083. if (onCompiled) {
  64084. onCompiled(_this);
  64085. }
  64086. return;
  64087. }
  64088. }
  64089. setTimeout(checkReady, 16);
  64090. };
  64091. checkReady();
  64092. };
  64093. /**
  64094. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  64095. * @param options Sets of optional options forcing the compilation with different modes
  64096. * @returns A promise that resolves when the compilation completes
  64097. */
  64098. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  64099. var _this = this;
  64100. return new Promise(function (resolve) {
  64101. _this.forceCompilation(function () {
  64102. resolve();
  64103. }, options);
  64104. });
  64105. };
  64106. /**
  64107. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  64108. * @param subMesh The submesh we want to render in the shadow map
  64109. * @param useInstances Defines wether will draw in the map using instances
  64110. * @returns true if ready otherwise, false
  64111. */
  64112. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  64113. var defines = [];
  64114. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  64115. defines.push("#define FLOAT");
  64116. }
  64117. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  64118. defines.push("#define ESM");
  64119. }
  64120. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  64121. defines.push("#define DEPTHTEXTURE");
  64122. }
  64123. var attribs = [BABYLON.VertexBuffer.PositionKind];
  64124. var mesh = subMesh.getMesh();
  64125. var material = subMesh.getMaterial();
  64126. // Normal bias.
  64127. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  64128. attribs.push(BABYLON.VertexBuffer.NormalKind);
  64129. defines.push("#define NORMAL");
  64130. if (mesh.nonUniformScaling) {
  64131. defines.push("#define NONUNIFORMSCALING");
  64132. }
  64133. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  64134. defines.push("#define DIRECTIONINLIGHTDATA");
  64135. }
  64136. }
  64137. // Alpha test
  64138. if (material && material.needAlphaTesting()) {
  64139. var alphaTexture = material.getAlphaTestTexture();
  64140. if (alphaTexture) {
  64141. defines.push("#define ALPHATEST");
  64142. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  64143. attribs.push(BABYLON.VertexBuffer.UVKind);
  64144. defines.push("#define UV1");
  64145. }
  64146. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  64147. if (alphaTexture.coordinatesIndex === 1) {
  64148. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  64149. defines.push("#define UV2");
  64150. }
  64151. }
  64152. }
  64153. }
  64154. // Bones
  64155. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  64156. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  64157. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  64158. if (mesh.numBoneInfluencers > 4) {
  64159. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  64160. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  64161. }
  64162. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  64163. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  64164. }
  64165. else {
  64166. defines.push("#define NUM_BONE_INFLUENCERS 0");
  64167. }
  64168. // Morph targets
  64169. var manager = mesh.morphTargetManager;
  64170. var morphInfluencers = 0;
  64171. if (manager) {
  64172. if (manager.numInfluencers > 0) {
  64173. defines.push("#define MORPHTARGETS");
  64174. morphInfluencers = manager.numInfluencers;
  64175. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  64176. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  64177. }
  64178. }
  64179. // Instances
  64180. if (useInstances) {
  64181. defines.push("#define INSTANCES");
  64182. attribs.push("world0");
  64183. attribs.push("world1");
  64184. attribs.push("world2");
  64185. attribs.push("world3");
  64186. }
  64187. // Get correct effect
  64188. var join = defines.join("\n");
  64189. if (this._cachedDefines !== join) {
  64190. this._cachedDefines = join;
  64191. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  64192. }
  64193. if (!this._effect.isReady()) {
  64194. return false;
  64195. }
  64196. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  64197. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  64198. this._initializeBlurRTTAndPostProcesses();
  64199. }
  64200. }
  64201. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  64202. return false;
  64203. }
  64204. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  64205. return false;
  64206. }
  64207. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  64208. return false;
  64209. }
  64210. return true;
  64211. };
  64212. /**
  64213. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  64214. * @param defines Defines of the material we want to update
  64215. * @param lightIndex Index of the light in the enabled light list of the material
  64216. */
  64217. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  64218. var scene = this._scene;
  64219. var light = this._light;
  64220. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  64221. return;
  64222. }
  64223. defines["SHADOW" + lightIndex] = true;
  64224. if (this.useContactHardeningShadow) {
  64225. defines["SHADOWPCSS" + lightIndex] = true;
  64226. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  64227. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  64228. }
  64229. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  64230. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  64231. }
  64232. // else default to high.
  64233. }
  64234. if (this.usePercentageCloserFiltering) {
  64235. defines["SHADOWPCF" + lightIndex] = true;
  64236. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  64237. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  64238. }
  64239. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  64240. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  64241. }
  64242. // else default to high.
  64243. }
  64244. else if (this.usePoissonSampling) {
  64245. defines["SHADOWPOISSON" + lightIndex] = true;
  64246. }
  64247. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  64248. defines["SHADOWESM" + lightIndex] = true;
  64249. }
  64250. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  64251. defines["SHADOWCLOSEESM" + lightIndex] = true;
  64252. }
  64253. if (light.needCube()) {
  64254. defines["SHADOWCUBE" + lightIndex] = true;
  64255. }
  64256. };
  64257. /**
  64258. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  64259. * defined in the generator but impacting the effect).
  64260. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  64261. * @param effect The effect we are binfing the information for
  64262. */
  64263. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  64264. var light = this._light;
  64265. var scene = this._scene;
  64266. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  64267. return;
  64268. }
  64269. var camera = scene.activeCamera;
  64270. if (!camera) {
  64271. return;
  64272. }
  64273. var shadowMap = this.getShadowMap();
  64274. if (!shadowMap) {
  64275. return;
  64276. }
  64277. if (!light.needCube()) {
  64278. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  64279. }
  64280. // Only PCF uses depth stencil texture.
  64281. if (this._filter === ShadowGenerator.FILTER_PCF) {
  64282. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  64283. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  64284. }
  64285. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  64286. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  64287. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  64288. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  64289. }
  64290. else {
  64291. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  64292. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  64293. }
  64294. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  64295. };
  64296. /**
  64297. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  64298. * (eq to shadow prjection matrix * light transform matrix)
  64299. * @returns The transform matrix used to create the shadow map
  64300. */
  64301. ShadowGenerator.prototype.getTransformMatrix = function () {
  64302. var scene = this._scene;
  64303. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  64304. return this._transformMatrix;
  64305. }
  64306. this._currentRenderID = scene.getRenderId();
  64307. this._currentFaceIndexCache = this._currentFaceIndex;
  64308. var lightPosition = this._light.position;
  64309. if (this._light.computeTransformedInformation()) {
  64310. lightPosition = this._light.transformedPosition;
  64311. }
  64312. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  64313. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  64314. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  64315. }
  64316. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  64317. this._cachedPosition.copyFrom(lightPosition);
  64318. this._cachedDirection.copyFrom(this._lightDirection);
  64319. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  64320. var shadowMap = this.getShadowMap();
  64321. if (shadowMap) {
  64322. var renderList = shadowMap.renderList;
  64323. if (renderList) {
  64324. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  64325. }
  64326. }
  64327. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  64328. }
  64329. return this._transformMatrix;
  64330. };
  64331. /**
  64332. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  64333. * Cube and 2D textures for instance.
  64334. */
  64335. ShadowGenerator.prototype.recreateShadowMap = function () {
  64336. var shadowMap = this._shadowMap;
  64337. if (!shadowMap) {
  64338. return;
  64339. }
  64340. // Track render list.
  64341. var renderList = shadowMap.renderList;
  64342. // Clean up existing data.
  64343. this._disposeRTTandPostProcesses();
  64344. // Reinitializes.
  64345. this._initializeGenerator();
  64346. // Reaffect the filter to ensure a correct fallback if necessary.
  64347. this.filter = this.filter;
  64348. // Reaffect the filter.
  64349. this._applyFilterValues();
  64350. // Reaffect Render List.
  64351. this._shadowMap.renderList = renderList;
  64352. };
  64353. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  64354. if (this._shadowMap2) {
  64355. this._shadowMap2.dispose();
  64356. this._shadowMap2 = null;
  64357. }
  64358. if (this._boxBlurPostprocess) {
  64359. this._boxBlurPostprocess.dispose();
  64360. this._boxBlurPostprocess = null;
  64361. }
  64362. if (this._kernelBlurXPostprocess) {
  64363. this._kernelBlurXPostprocess.dispose();
  64364. this._kernelBlurXPostprocess = null;
  64365. }
  64366. if (this._kernelBlurYPostprocess) {
  64367. this._kernelBlurYPostprocess.dispose();
  64368. this._kernelBlurYPostprocess = null;
  64369. }
  64370. this._blurPostProcesses = [];
  64371. };
  64372. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  64373. if (this._shadowMap) {
  64374. this._shadowMap.dispose();
  64375. this._shadowMap = null;
  64376. }
  64377. this._disposeBlurPostProcesses();
  64378. };
  64379. /**
  64380. * Disposes the ShadowGenerator.
  64381. * Returns nothing.
  64382. */
  64383. ShadowGenerator.prototype.dispose = function () {
  64384. this._disposeRTTandPostProcesses();
  64385. if (this._light) {
  64386. this._light._shadowGenerator = null;
  64387. this._light._markMeshesAsLightDirty();
  64388. }
  64389. };
  64390. /**
  64391. * Serializes the shadow generator setup to a json object.
  64392. * @returns The serialized JSON object
  64393. */
  64394. ShadowGenerator.prototype.serialize = function () {
  64395. var serializationObject = {};
  64396. var shadowMap = this.getShadowMap();
  64397. if (!shadowMap) {
  64398. return serializationObject;
  64399. }
  64400. serializationObject.lightId = this._light.id;
  64401. serializationObject.mapSize = shadowMap.getRenderSize();
  64402. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  64403. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  64404. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  64405. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  64406. serializationObject.usePoissonSampling = this.usePoissonSampling;
  64407. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  64408. serializationObject.depthScale = this.depthScale;
  64409. serializationObject.darkness = this.getDarkness();
  64410. serializationObject.blurBoxOffset = this.blurBoxOffset;
  64411. serializationObject.blurKernel = this.blurKernel;
  64412. serializationObject.blurScale = this.blurScale;
  64413. serializationObject.useKernelBlur = this.useKernelBlur;
  64414. serializationObject.transparencyShadow = this._transparencyShadow;
  64415. serializationObject.bias = this.bias;
  64416. serializationObject.normalBias = this.normalBias;
  64417. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  64418. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  64419. serializationObject.filteringQuality = this.filteringQuality;
  64420. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  64421. serializationObject.renderList = [];
  64422. if (shadowMap.renderList) {
  64423. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  64424. var mesh = shadowMap.renderList[meshIndex];
  64425. serializationObject.renderList.push(mesh.id);
  64426. }
  64427. }
  64428. return serializationObject;
  64429. };
  64430. /**
  64431. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  64432. * @param parsedShadowGenerator The JSON object to parse
  64433. * @param scene The scene to create the shadow map for
  64434. * @returns The parsed shadow generator
  64435. */
  64436. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  64437. //casting to point light, as light is missing the position attr and typescript complains.
  64438. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  64439. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  64440. var shadowMap = shadowGenerator.getShadowMap();
  64441. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  64442. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  64443. meshes.forEach(function (mesh) {
  64444. if (!shadowMap) {
  64445. return;
  64446. }
  64447. if (!shadowMap.renderList) {
  64448. shadowMap.renderList = [];
  64449. }
  64450. shadowMap.renderList.push(mesh);
  64451. });
  64452. }
  64453. if (parsedShadowGenerator.usePoissonSampling) {
  64454. shadowGenerator.usePoissonSampling = true;
  64455. }
  64456. else if (parsedShadowGenerator.useExponentialShadowMap) {
  64457. shadowGenerator.useExponentialShadowMap = true;
  64458. }
  64459. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  64460. shadowGenerator.useBlurExponentialShadowMap = true;
  64461. }
  64462. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  64463. shadowGenerator.useCloseExponentialShadowMap = true;
  64464. }
  64465. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  64466. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  64467. }
  64468. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  64469. shadowGenerator.usePercentageCloserFiltering = true;
  64470. }
  64471. else if (parsedShadowGenerator.useContactHardeningShadow) {
  64472. shadowGenerator.useContactHardeningShadow = true;
  64473. }
  64474. if (parsedShadowGenerator.filteringQuality) {
  64475. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  64476. }
  64477. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  64478. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  64479. }
  64480. else if (parsedShadowGenerator.useVarianceShadowMap) {
  64481. shadowGenerator.useExponentialShadowMap = true;
  64482. }
  64483. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  64484. shadowGenerator.useBlurExponentialShadowMap = true;
  64485. }
  64486. if (parsedShadowGenerator.depthScale) {
  64487. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  64488. }
  64489. if (parsedShadowGenerator.blurScale) {
  64490. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  64491. }
  64492. if (parsedShadowGenerator.blurBoxOffset) {
  64493. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  64494. }
  64495. if (parsedShadowGenerator.useKernelBlur) {
  64496. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  64497. }
  64498. if (parsedShadowGenerator.blurKernel) {
  64499. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  64500. }
  64501. if (parsedShadowGenerator.bias !== undefined) {
  64502. shadowGenerator.bias = parsedShadowGenerator.bias;
  64503. }
  64504. if (parsedShadowGenerator.normalBias !== undefined) {
  64505. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  64506. }
  64507. if (parsedShadowGenerator.darkness) {
  64508. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  64509. }
  64510. if (parsedShadowGenerator.transparencyShadow) {
  64511. shadowGenerator.setTransparencyShadow(true);
  64512. }
  64513. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  64514. return shadowGenerator;
  64515. };
  64516. /**
  64517. * Shadow generator mode None: no filtering applied.
  64518. */
  64519. ShadowGenerator.FILTER_NONE = 0;
  64520. /**
  64521. * Shadow generator mode ESM: Exponential Shadow Mapping.
  64522. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  64523. */
  64524. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  64525. /**
  64526. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  64527. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  64528. */
  64529. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  64530. /**
  64531. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  64532. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  64533. */
  64534. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  64535. /**
  64536. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  64537. * edge artifacts on steep falloff.
  64538. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  64539. */
  64540. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  64541. /**
  64542. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  64543. * edge artifacts on steep falloff.
  64544. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  64545. */
  64546. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  64547. /**
  64548. * Shadow generator mode PCF: Percentage Closer Filtering
  64549. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  64550. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  64551. */
  64552. ShadowGenerator.FILTER_PCF = 6;
  64553. /**
  64554. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  64555. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  64556. * Contact Hardening
  64557. */
  64558. ShadowGenerator.FILTER_PCSS = 7;
  64559. /**
  64560. * Reserved for PCF and PCSS
  64561. * Highest Quality.
  64562. *
  64563. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  64564. *
  64565. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  64566. */
  64567. ShadowGenerator.QUALITY_HIGH = 0;
  64568. /**
  64569. * Reserved for PCF and PCSS
  64570. * Good tradeoff for quality/perf cross devices
  64571. *
  64572. * Execute PCF on a 3*3 kernel.
  64573. *
  64574. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  64575. */
  64576. ShadowGenerator.QUALITY_MEDIUM = 1;
  64577. /**
  64578. * Reserved for PCF and PCSS
  64579. * The lowest quality but the fastest.
  64580. *
  64581. * Execute PCF on a 1*1 kernel.
  64582. *
  64583. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  64584. */
  64585. ShadowGenerator.QUALITY_LOW = 2;
  64586. return ShadowGenerator;
  64587. }());
  64588. BABYLON.ShadowGenerator = ShadowGenerator;
  64589. })(BABYLON || (BABYLON = {}));
  64590. //# sourceMappingURL=babylon.shadowGenerator.js.map
  64591. "use strict";
  64592. var BABYLON;
  64593. (function (BABYLON) {
  64594. var DefaultLoadingScreen = /** @class */ (function () {
  64595. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  64596. if (_loadingText === void 0) { _loadingText = ""; }
  64597. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  64598. var _this = this;
  64599. this._renderingCanvas = _renderingCanvas;
  64600. this._loadingText = _loadingText;
  64601. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  64602. // Resize
  64603. this._resizeLoadingUI = function () {
  64604. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  64605. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  64606. if (!_this._loadingDiv) {
  64607. return;
  64608. }
  64609. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  64610. _this._loadingDiv.style.left = canvasRect.left + "px";
  64611. _this._loadingDiv.style.top = canvasRect.top + "px";
  64612. _this._loadingDiv.style.width = canvasRect.width + "px";
  64613. _this._loadingDiv.style.height = canvasRect.height + "px";
  64614. };
  64615. }
  64616. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  64617. if (this._loadingDiv) {
  64618. // Do not add a loading screen if there is already one
  64619. return;
  64620. }
  64621. this._loadingDiv = document.createElement("div");
  64622. this._loadingDiv.id = "babylonjsLoadingDiv";
  64623. this._loadingDiv.style.opacity = "0";
  64624. this._loadingDiv.style.transition = "opacity 1.5s ease";
  64625. this._loadingDiv.style.pointerEvents = "none";
  64626. // Loading text
  64627. this._loadingTextDiv = document.createElement("div");
  64628. this._loadingTextDiv.style.position = "absolute";
  64629. this._loadingTextDiv.style.left = "0";
  64630. this._loadingTextDiv.style.top = "50%";
  64631. this._loadingTextDiv.style.marginTop = "80px";
  64632. this._loadingTextDiv.style.width = "100%";
  64633. this._loadingTextDiv.style.height = "20px";
  64634. this._loadingTextDiv.style.fontFamily = "Arial";
  64635. this._loadingTextDiv.style.fontSize = "14px";
  64636. this._loadingTextDiv.style.color = "white";
  64637. this._loadingTextDiv.style.textAlign = "center";
  64638. this._loadingTextDiv.innerHTML = "Loading";
  64639. this._loadingDiv.appendChild(this._loadingTextDiv);
  64640. //set the predefined text
  64641. this._loadingTextDiv.innerHTML = this._loadingText;
  64642. // Generating keyframes
  64643. var style = document.createElement('style');
  64644. style.type = 'text/css';
  64645. 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 }";
  64646. style.innerHTML = keyFrames;
  64647. document.getElementsByTagName('head')[0].appendChild(style);
  64648. // Loading img
  64649. var imgBack = new Image();
  64650. 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";
  64651. imgBack.style.position = "absolute";
  64652. imgBack.style.left = "50%";
  64653. imgBack.style.top = "50%";
  64654. imgBack.style.marginLeft = "-60px";
  64655. imgBack.style.marginTop = "-60px";
  64656. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  64657. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  64658. imgBack.style.transformOrigin = "50% 50%";
  64659. imgBack.style.webkitTransformOrigin = "50% 50%";
  64660. this._loadingDiv.appendChild(imgBack);
  64661. this._resizeLoadingUI();
  64662. window.addEventListener("resize", this._resizeLoadingUI);
  64663. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  64664. document.body.appendChild(this._loadingDiv);
  64665. this._loadingDiv.style.opacity = "1";
  64666. };
  64667. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  64668. var _this = this;
  64669. if (!this._loadingDiv) {
  64670. return;
  64671. }
  64672. var onTransitionEnd = function () {
  64673. if (!_this._loadingDiv) {
  64674. return;
  64675. }
  64676. document.body.removeChild(_this._loadingDiv);
  64677. window.removeEventListener("resize", _this._resizeLoadingUI);
  64678. _this._loadingDiv = null;
  64679. };
  64680. this._loadingDiv.style.opacity = "0";
  64681. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  64682. };
  64683. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  64684. set: function (text) {
  64685. this._loadingText = text;
  64686. if (this._loadingTextDiv) {
  64687. this._loadingTextDiv.innerHTML = this._loadingText;
  64688. }
  64689. },
  64690. enumerable: true,
  64691. configurable: true
  64692. });
  64693. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  64694. get: function () {
  64695. return this._loadingDivBackgroundColor;
  64696. },
  64697. set: function (color) {
  64698. this._loadingDivBackgroundColor = color;
  64699. if (!this._loadingDiv) {
  64700. return;
  64701. }
  64702. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  64703. },
  64704. enumerable: true,
  64705. configurable: true
  64706. });
  64707. return DefaultLoadingScreen;
  64708. }());
  64709. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  64710. })(BABYLON || (BABYLON = {}));
  64711. //# sourceMappingURL=babylon.loadingScreen.js.map
  64712. "use strict";
  64713. var BABYLON;
  64714. (function (BABYLON) {
  64715. var SceneLoaderProgressEvent = /** @class */ (function () {
  64716. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  64717. this.lengthComputable = lengthComputable;
  64718. this.loaded = loaded;
  64719. this.total = total;
  64720. }
  64721. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  64722. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  64723. };
  64724. return SceneLoaderProgressEvent;
  64725. }());
  64726. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  64727. var SceneLoader = /** @class */ (function () {
  64728. function SceneLoader() {
  64729. }
  64730. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  64731. get: function () {
  64732. return 0;
  64733. },
  64734. enumerable: true,
  64735. configurable: true
  64736. });
  64737. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  64738. get: function () {
  64739. return 1;
  64740. },
  64741. enumerable: true,
  64742. configurable: true
  64743. });
  64744. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  64745. get: function () {
  64746. return 2;
  64747. },
  64748. enumerable: true,
  64749. configurable: true
  64750. });
  64751. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  64752. get: function () {
  64753. return 3;
  64754. },
  64755. enumerable: true,
  64756. configurable: true
  64757. });
  64758. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  64759. get: function () {
  64760. return SceneLoader._ForceFullSceneLoadingForIncremental;
  64761. },
  64762. set: function (value) {
  64763. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  64764. },
  64765. enumerable: true,
  64766. configurable: true
  64767. });
  64768. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  64769. get: function () {
  64770. return SceneLoader._ShowLoadingScreen;
  64771. },
  64772. set: function (value) {
  64773. SceneLoader._ShowLoadingScreen = value;
  64774. },
  64775. enumerable: true,
  64776. configurable: true
  64777. });
  64778. Object.defineProperty(SceneLoader, "loggingLevel", {
  64779. get: function () {
  64780. return SceneLoader._loggingLevel;
  64781. },
  64782. set: function (value) {
  64783. SceneLoader._loggingLevel = value;
  64784. },
  64785. enumerable: true,
  64786. configurable: true
  64787. });
  64788. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  64789. get: function () {
  64790. return SceneLoader._CleanBoneMatrixWeights;
  64791. },
  64792. set: function (value) {
  64793. SceneLoader._CleanBoneMatrixWeights = value;
  64794. },
  64795. enumerable: true,
  64796. configurable: true
  64797. });
  64798. SceneLoader._getDefaultPlugin = function () {
  64799. return SceneLoader._registeredPlugins[".babylon"];
  64800. };
  64801. SceneLoader._getPluginForExtension = function (extension) {
  64802. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  64803. if (registeredPlugin) {
  64804. return registeredPlugin;
  64805. }
  64806. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  64807. return SceneLoader._getDefaultPlugin();
  64808. };
  64809. SceneLoader._getPluginForDirectLoad = function (data) {
  64810. for (var extension in SceneLoader._registeredPlugins) {
  64811. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  64812. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  64813. return SceneLoader._registeredPlugins[extension];
  64814. }
  64815. }
  64816. return SceneLoader._getDefaultPlugin();
  64817. };
  64818. SceneLoader._getPluginForFilename = function (sceneFilename) {
  64819. if (sceneFilename.name) {
  64820. sceneFilename = sceneFilename.name;
  64821. }
  64822. var queryStringPosition = sceneFilename.indexOf("?");
  64823. if (queryStringPosition !== -1) {
  64824. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  64825. }
  64826. var dotPosition = sceneFilename.lastIndexOf(".");
  64827. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  64828. return SceneLoader._getPluginForExtension(extension);
  64829. };
  64830. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  64831. SceneLoader._getDirectLoad = function (sceneFilename) {
  64832. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  64833. return sceneFilename.substr(5);
  64834. }
  64835. return null;
  64836. };
  64837. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  64838. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  64839. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  64840. var plugin;
  64841. if (registeredPlugin.plugin.createPlugin) {
  64842. plugin = registeredPlugin.plugin.createPlugin();
  64843. }
  64844. else {
  64845. plugin = registeredPlugin.plugin;
  64846. }
  64847. var useArrayBuffer = registeredPlugin.isBinary;
  64848. var database;
  64849. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  64850. var dataCallback = function (data, responseURL) {
  64851. if (scene.isDisposed) {
  64852. onError("Scene has been disposed");
  64853. return;
  64854. }
  64855. scene.database = database;
  64856. onSuccess(plugin, data, responseURL);
  64857. };
  64858. var request = null;
  64859. var pluginDisposed = false;
  64860. var onDisposeObservable = plugin.onDisposeObservable;
  64861. if (onDisposeObservable) {
  64862. onDisposeObservable.add(function () {
  64863. pluginDisposed = true;
  64864. if (request) {
  64865. request.abort();
  64866. request = null;
  64867. }
  64868. onDispose();
  64869. });
  64870. }
  64871. var manifestChecked = function () {
  64872. if (pluginDisposed) {
  64873. return;
  64874. }
  64875. var url = rootUrl + sceneFilename;
  64876. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  64877. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  64878. } : undefined, database, useArrayBuffer, function (request, exception) {
  64879. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  64880. });
  64881. };
  64882. if (directLoad) {
  64883. dataCallback(directLoad);
  64884. return plugin;
  64885. }
  64886. if (rootUrl.indexOf("file:") === -1) {
  64887. var canUseOfflineSupport = scene.getEngine().enableOfflineSupport;
  64888. if (canUseOfflineSupport) {
  64889. // Also check for exceptions
  64890. var exceptionFound = false;
  64891. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  64892. var regex = _a[_i];
  64893. if (regex.test(rootUrl + sceneFilename)) {
  64894. exceptionFound = true;
  64895. break;
  64896. }
  64897. }
  64898. canUseOfflineSupport = !exceptionFound;
  64899. }
  64900. if (canUseOfflineSupport) {
  64901. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  64902. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  64903. }
  64904. else {
  64905. manifestChecked();
  64906. }
  64907. }
  64908. else {
  64909. var fileOrString = sceneFilename;
  64910. if (fileOrString.name) {
  64911. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  64912. }
  64913. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  64914. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  64915. }
  64916. else {
  64917. onError("Unable to find file named " + sceneFilename);
  64918. }
  64919. }
  64920. return plugin;
  64921. };
  64922. // Public functions
  64923. SceneLoader.GetPluginForExtension = function (extension) {
  64924. return SceneLoader._getPluginForExtension(extension).plugin;
  64925. };
  64926. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  64927. return !!SceneLoader._registeredPlugins[extension];
  64928. };
  64929. SceneLoader.RegisterPlugin = function (plugin) {
  64930. if (typeof plugin.extensions === "string") {
  64931. var extension = plugin.extensions;
  64932. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  64933. plugin: plugin,
  64934. isBinary: false
  64935. };
  64936. }
  64937. else {
  64938. var extensions = plugin.extensions;
  64939. Object.keys(extensions).forEach(function (extension) {
  64940. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  64941. plugin: plugin,
  64942. isBinary: extensions[extension].isBinary
  64943. };
  64944. });
  64945. }
  64946. };
  64947. /**
  64948. * Import meshes into a scene
  64949. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  64950. * @param rootUrl a string that defines the root url for scene and resources
  64951. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  64952. * @param scene the instance of BABYLON.Scene to append to
  64953. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  64954. * @param onProgress a callback with a progress event for each file being loaded
  64955. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  64956. * @param pluginExtension the extension used to determine the plugin
  64957. * @returns The loaded plugin
  64958. */
  64959. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  64960. if (onSuccess === void 0) { onSuccess = null; }
  64961. if (onProgress === void 0) { onProgress = null; }
  64962. if (onError === void 0) { onError = null; }
  64963. if (pluginExtension === void 0) { pluginExtension = null; }
  64964. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  64965. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  64966. return null;
  64967. }
  64968. var loadingToken = {};
  64969. scene._addPendingData(loadingToken);
  64970. var disposeHandler = function () {
  64971. scene._removePendingData(loadingToken);
  64972. };
  64973. var errorHandler = function (message, exception) {
  64974. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  64975. if (onError) {
  64976. onError(scene, errorMessage, exception);
  64977. }
  64978. else {
  64979. BABYLON.Tools.Error(errorMessage);
  64980. // should the exception be thrown?
  64981. }
  64982. disposeHandler();
  64983. };
  64984. var progressHandler = onProgress ? function (event) {
  64985. try {
  64986. onProgress(event);
  64987. }
  64988. catch (e) {
  64989. errorHandler("Error in onProgress callback", e);
  64990. }
  64991. } : undefined;
  64992. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  64993. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  64994. if (onSuccess) {
  64995. try {
  64996. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  64997. }
  64998. catch (e) {
  64999. errorHandler("Error in onSuccess callback", e);
  65000. }
  65001. }
  65002. scene._removePendingData(loadingToken);
  65003. };
  65004. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  65005. if (plugin.rewriteRootURL) {
  65006. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  65007. }
  65008. if (sceneFilename === "") {
  65009. if (sceneFilename === "") {
  65010. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  65011. }
  65012. }
  65013. if (plugin.importMesh) {
  65014. var syncedPlugin = plugin;
  65015. var meshes = new Array();
  65016. var particleSystems = new Array();
  65017. var skeletons = new Array();
  65018. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  65019. return;
  65020. }
  65021. scene.loadingPluginName = plugin.name;
  65022. successHandler(meshes, particleSystems, skeletons, []);
  65023. }
  65024. else {
  65025. var asyncedPlugin = plugin;
  65026. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  65027. scene.loadingPluginName = plugin.name;
  65028. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  65029. }).catch(function (error) {
  65030. errorHandler(error.message, error);
  65031. });
  65032. }
  65033. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  65034. };
  65035. /**
  65036. * Import meshes into a scene
  65037. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  65038. * @param rootUrl a string that defines the root url for scene and resources
  65039. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  65040. * @param scene the instance of BABYLON.Scene to append to
  65041. * @param onProgress a callback with a progress event for each file being loaded
  65042. * @param pluginExtension the extension used to determine the plugin
  65043. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  65044. */
  65045. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  65046. if (onProgress === void 0) { onProgress = null; }
  65047. if (pluginExtension === void 0) { pluginExtension = null; }
  65048. return new Promise(function (resolve, reject) {
  65049. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  65050. resolve({
  65051. meshes: meshes,
  65052. particleSystems: particleSystems,
  65053. skeletons: skeletons,
  65054. animationGroups: animationGroups
  65055. });
  65056. }, onProgress, function (scene, message, exception) {
  65057. reject(exception || new Error(message));
  65058. });
  65059. });
  65060. };
  65061. /**
  65062. * Load a scene
  65063. * @param rootUrl a string that defines the root url for scene and resources
  65064. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  65065. * @param engine is the instance of BABYLON.Engine to use to create the scene
  65066. * @param onSuccess a callback with the scene when import succeeds
  65067. * @param onProgress a callback with a progress event for each file being loaded
  65068. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  65069. * @param pluginExtension the extension used to determine the plugin
  65070. * @returns The loaded plugin
  65071. */
  65072. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  65073. if (onSuccess === void 0) { onSuccess = null; }
  65074. if (onProgress === void 0) { onProgress = null; }
  65075. if (onError === void 0) { onError = null; }
  65076. if (pluginExtension === void 0) { pluginExtension = null; }
  65077. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  65078. };
  65079. /**
  65080. * Load a scene
  65081. * @param rootUrl a string that defines the root url for scene and resources
  65082. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  65083. * @param engine is the instance of BABYLON.Engine to use to create the scene
  65084. * @param onProgress a callback with a progress event for each file being loaded
  65085. * @param pluginExtension the extension used to determine the plugin
  65086. * @returns The loaded scene
  65087. */
  65088. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  65089. if (onProgress === void 0) { onProgress = null; }
  65090. if (pluginExtension === void 0) { pluginExtension = null; }
  65091. return new Promise(function (resolve, reject) {
  65092. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  65093. resolve(scene);
  65094. }, onProgress, function (scene, message, exception) {
  65095. reject(exception || new Error(message));
  65096. }, pluginExtension);
  65097. });
  65098. };
  65099. /**
  65100. * Append a scene
  65101. * @param rootUrl a string that defines the root url for scene and resources
  65102. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  65103. * @param scene is the instance of BABYLON.Scene to append to
  65104. * @param onSuccess a callback with the scene when import succeeds
  65105. * @param onProgress a callback with a progress event for each file being loaded
  65106. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  65107. * @param pluginExtension the extension used to determine the plugin
  65108. * @returns The loaded plugin
  65109. */
  65110. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  65111. if (onSuccess === void 0) { onSuccess = null; }
  65112. if (onProgress === void 0) { onProgress = null; }
  65113. if (onError === void 0) { onError = null; }
  65114. if (pluginExtension === void 0) { pluginExtension = null; }
  65115. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  65116. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  65117. return null;
  65118. }
  65119. if (SceneLoader.ShowLoadingScreen) {
  65120. scene.getEngine().displayLoadingUI();
  65121. }
  65122. var loadingToken = {};
  65123. scene._addPendingData(loadingToken);
  65124. var disposeHandler = function () {
  65125. scene._removePendingData(loadingToken);
  65126. scene.getEngine().hideLoadingUI();
  65127. };
  65128. var errorHandler = function (message, exception) {
  65129. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  65130. if (onError) {
  65131. onError(scene, errorMessage, exception);
  65132. }
  65133. else {
  65134. BABYLON.Tools.Error(errorMessage);
  65135. // should the exception be thrown?
  65136. }
  65137. disposeHandler();
  65138. };
  65139. var progressHandler = onProgress ? function (event) {
  65140. try {
  65141. onProgress(event);
  65142. }
  65143. catch (e) {
  65144. errorHandler("Error in onProgress callback", e);
  65145. }
  65146. } : undefined;
  65147. var successHandler = function () {
  65148. if (onSuccess) {
  65149. try {
  65150. onSuccess(scene);
  65151. }
  65152. catch (e) {
  65153. errorHandler("Error in onSuccess callback", e);
  65154. }
  65155. }
  65156. scene._removePendingData(loadingToken);
  65157. };
  65158. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  65159. if (sceneFilename === "") {
  65160. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  65161. }
  65162. if (plugin.load) {
  65163. var syncedPlugin = plugin;
  65164. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  65165. return;
  65166. }
  65167. scene.loadingPluginName = plugin.name;
  65168. successHandler();
  65169. }
  65170. else {
  65171. var asyncedPlugin = plugin;
  65172. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  65173. scene.loadingPluginName = plugin.name;
  65174. successHandler();
  65175. }).catch(function (error) {
  65176. errorHandler(error.message, error);
  65177. });
  65178. }
  65179. if (SceneLoader.ShowLoadingScreen) {
  65180. scene.executeWhenReady(function () {
  65181. scene.getEngine().hideLoadingUI();
  65182. });
  65183. }
  65184. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  65185. };
  65186. /**
  65187. * Append a scene
  65188. * @param rootUrl a string that defines the root url for scene and resources
  65189. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  65190. * @param scene is the instance of BABYLON.Scene to append to
  65191. * @param onProgress a callback with a progress event for each file being loaded
  65192. * @param pluginExtension the extension used to determine the plugin
  65193. * @returns The given scene
  65194. */
  65195. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  65196. if (onProgress === void 0) { onProgress = null; }
  65197. if (pluginExtension === void 0) { pluginExtension = null; }
  65198. return new Promise(function (resolve, reject) {
  65199. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  65200. resolve(scene);
  65201. }, onProgress, function (scene, message, exception) {
  65202. reject(exception || new Error(message));
  65203. }, pluginExtension);
  65204. });
  65205. };
  65206. /**
  65207. * Load a scene into an asset container
  65208. * @param rootUrl a string that defines the root url for scene and resources
  65209. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  65210. * @param scene is the instance of BABYLON.Scene to append to
  65211. * @param onSuccess a callback with the scene when import succeeds
  65212. * @param onProgress a callback with a progress event for each file being loaded
  65213. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  65214. * @param pluginExtension the extension used to determine the plugin
  65215. * @returns The loaded plugin
  65216. */
  65217. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  65218. if (onSuccess === void 0) { onSuccess = null; }
  65219. if (onProgress === void 0) { onProgress = null; }
  65220. if (onError === void 0) { onError = null; }
  65221. if (pluginExtension === void 0) { pluginExtension = null; }
  65222. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  65223. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  65224. return null;
  65225. }
  65226. var loadingToken = {};
  65227. scene._addPendingData(loadingToken);
  65228. var disposeHandler = function () {
  65229. scene._removePendingData(loadingToken);
  65230. };
  65231. var errorHandler = function (message, exception) {
  65232. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  65233. if (onError) {
  65234. onError(scene, errorMessage, exception);
  65235. }
  65236. else {
  65237. BABYLON.Tools.Error(errorMessage);
  65238. // should the exception be thrown?
  65239. }
  65240. disposeHandler();
  65241. };
  65242. var progressHandler = onProgress ? function (event) {
  65243. try {
  65244. onProgress(event);
  65245. }
  65246. catch (e) {
  65247. errorHandler("Error in onProgress callback", e);
  65248. }
  65249. } : undefined;
  65250. var successHandler = function (assets) {
  65251. if (onSuccess) {
  65252. try {
  65253. onSuccess(assets);
  65254. }
  65255. catch (e) {
  65256. errorHandler("Error in onSuccess callback", e);
  65257. }
  65258. }
  65259. scene._removePendingData(loadingToken);
  65260. };
  65261. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  65262. if (plugin.loadAssetContainer) {
  65263. var syncedPlugin = plugin;
  65264. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  65265. if (!assetContainer) {
  65266. return;
  65267. }
  65268. scene.loadingPluginName = plugin.name;
  65269. successHandler(assetContainer);
  65270. }
  65271. else if (plugin.loadAssetContainerAsync) {
  65272. var asyncedPlugin = plugin;
  65273. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  65274. scene.loadingPluginName = plugin.name;
  65275. successHandler(assetContainer);
  65276. }).catch(function (error) {
  65277. errorHandler(error.message, error);
  65278. });
  65279. }
  65280. else {
  65281. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  65282. }
  65283. if (SceneLoader.ShowLoadingScreen) {
  65284. scene.executeWhenReady(function () {
  65285. scene.getEngine().hideLoadingUI();
  65286. });
  65287. }
  65288. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  65289. };
  65290. /**
  65291. * Load a scene into an asset container
  65292. * @param rootUrl a string that defines the root url for scene and resources
  65293. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  65294. * @param scene is the instance of BABYLON.Scene to append to
  65295. * @param onProgress a callback with a progress event for each file being loaded
  65296. * @param pluginExtension the extension used to determine the plugin
  65297. * @returns The loaded asset container
  65298. */
  65299. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  65300. if (onProgress === void 0) { onProgress = null; }
  65301. if (pluginExtension === void 0) { pluginExtension = null; }
  65302. return new Promise(function (resolve, reject) {
  65303. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  65304. resolve(assetContainer);
  65305. }, onProgress, function (scene, message, exception) {
  65306. reject(exception || new Error(message));
  65307. }, pluginExtension);
  65308. });
  65309. };
  65310. // Flags
  65311. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  65312. SceneLoader._ShowLoadingScreen = true;
  65313. SceneLoader._CleanBoneMatrixWeights = false;
  65314. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  65315. // Members
  65316. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  65317. SceneLoader._registeredPlugins = {};
  65318. return SceneLoader;
  65319. }());
  65320. BABYLON.SceneLoader = SceneLoader;
  65321. ;
  65322. })(BABYLON || (BABYLON = {}));
  65323. //# sourceMappingURL=babylon.sceneLoader.js.map
  65324. "use strict";
  65325. var BABYLON;
  65326. (function (BABYLON) {
  65327. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  65328. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  65329. var parsedMaterial = parsedData.materials[index];
  65330. if (parsedMaterial.id === id) {
  65331. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  65332. }
  65333. }
  65334. return null;
  65335. };
  65336. var isDescendantOf = function (mesh, names, hierarchyIds) {
  65337. for (var i in names) {
  65338. if (mesh.name === names[i]) {
  65339. hierarchyIds.push(mesh.id);
  65340. return true;
  65341. }
  65342. }
  65343. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  65344. hierarchyIds.push(mesh.id);
  65345. return true;
  65346. }
  65347. return false;
  65348. };
  65349. var logOperation = function (operation, producer) {
  65350. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  65351. };
  65352. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  65353. if (addToScene === void 0) { addToScene = false; }
  65354. var container = new BABYLON.AssetContainer(scene);
  65355. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  65356. // when SceneLoader.debugLogging = true (default), or exception encountered.
  65357. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  65358. // and avoid problems with multiple concurrent .babylon loads.
  65359. var log = "importScene has failed JSON parse";
  65360. try {
  65361. var parsedData = JSON.parse(data);
  65362. log = "";
  65363. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  65364. var index;
  65365. var cache;
  65366. // Lights
  65367. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  65368. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  65369. var parsedLight = parsedData.lights[index];
  65370. var light = BABYLON.Light.Parse(parsedLight, scene);
  65371. if (light) {
  65372. container.lights.push(light);
  65373. log += (index === 0 ? "\n\tLights:" : "");
  65374. log += "\n\t\t" + light.toString(fullDetails);
  65375. }
  65376. }
  65377. }
  65378. // Animations
  65379. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  65380. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  65381. var parsedAnimation = parsedData.animations[index];
  65382. var animation = BABYLON.Animation.Parse(parsedAnimation);
  65383. scene.animations.push(animation);
  65384. container.animations.push(animation);
  65385. log += (index === 0 ? "\n\tAnimations:" : "");
  65386. log += "\n\t\t" + animation.toString(fullDetails);
  65387. }
  65388. }
  65389. // Materials
  65390. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  65391. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  65392. var parsedMaterial = parsedData.materials[index];
  65393. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  65394. container.materials.push(mat);
  65395. log += (index === 0 ? "\n\tMaterials:" : "");
  65396. log += "\n\t\t" + mat.toString(fullDetails);
  65397. }
  65398. }
  65399. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  65400. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  65401. var parsedMultiMaterial = parsedData.multiMaterials[index];
  65402. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  65403. container.multiMaterials.push(mmat);
  65404. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  65405. log += "\n\t\t" + mmat.toString(fullDetails);
  65406. }
  65407. }
  65408. // Morph targets
  65409. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  65410. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  65411. var managerData = _a[_i];
  65412. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  65413. }
  65414. }
  65415. // Skeletons
  65416. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  65417. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  65418. var parsedSkeleton = parsedData.skeletons[index];
  65419. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  65420. container.skeletons.push(skeleton);
  65421. log += (index === 0 ? "\n\tSkeletons:" : "");
  65422. log += "\n\t\t" + skeleton.toString(fullDetails);
  65423. }
  65424. }
  65425. // Geometries
  65426. var geometries = parsedData.geometries;
  65427. if (geometries !== undefined && geometries !== null) {
  65428. var addedGeometry = new Array();
  65429. // Boxes
  65430. var boxes = geometries.boxes;
  65431. if (boxes !== undefined && boxes !== null) {
  65432. for (index = 0, cache = boxes.length; index < cache; index++) {
  65433. var parsedBox = boxes[index];
  65434. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  65435. }
  65436. }
  65437. // Spheres
  65438. var spheres = geometries.spheres;
  65439. if (spheres !== undefined && spheres !== null) {
  65440. for (index = 0, cache = spheres.length; index < cache; index++) {
  65441. var parsedSphere = spheres[index];
  65442. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  65443. }
  65444. }
  65445. // Cylinders
  65446. var cylinders = geometries.cylinders;
  65447. if (cylinders !== undefined && cylinders !== null) {
  65448. for (index = 0, cache = cylinders.length; index < cache; index++) {
  65449. var parsedCylinder = cylinders[index];
  65450. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  65451. }
  65452. }
  65453. // Toruses
  65454. var toruses = geometries.toruses;
  65455. if (toruses !== undefined && toruses !== null) {
  65456. for (index = 0, cache = toruses.length; index < cache; index++) {
  65457. var parsedTorus = toruses[index];
  65458. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  65459. }
  65460. }
  65461. // Grounds
  65462. var grounds = geometries.grounds;
  65463. if (grounds !== undefined && grounds !== null) {
  65464. for (index = 0, cache = grounds.length; index < cache; index++) {
  65465. var parsedGround = grounds[index];
  65466. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  65467. }
  65468. }
  65469. // Planes
  65470. var planes = geometries.planes;
  65471. if (planes !== undefined && planes !== null) {
  65472. for (index = 0, cache = planes.length; index < cache; index++) {
  65473. var parsedPlane = planes[index];
  65474. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  65475. }
  65476. }
  65477. // TorusKnots
  65478. var torusKnots = geometries.torusKnots;
  65479. if (torusKnots !== undefined && torusKnots !== null) {
  65480. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  65481. var parsedTorusKnot = torusKnots[index];
  65482. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  65483. }
  65484. }
  65485. // VertexData
  65486. var vertexData = geometries.vertexData;
  65487. if (vertexData !== undefined && vertexData !== null) {
  65488. for (index = 0, cache = vertexData.length; index < cache; index++) {
  65489. var parsedVertexData = vertexData[index];
  65490. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  65491. }
  65492. }
  65493. addedGeometry.forEach(function (g) {
  65494. if (g) {
  65495. container.geometries.push(g);
  65496. }
  65497. });
  65498. }
  65499. // Transform nodes
  65500. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  65501. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  65502. var parsedTransformNode = parsedData.transformNodes[index];
  65503. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  65504. container.transformNodes.push(node);
  65505. }
  65506. }
  65507. // Meshes
  65508. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  65509. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  65510. var parsedMesh = parsedData.meshes[index];
  65511. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  65512. container.meshes.push(mesh);
  65513. log += (index === 0 ? "\n\tMeshes:" : "");
  65514. log += "\n\t\t" + mesh.toString(fullDetails);
  65515. }
  65516. }
  65517. // Cameras
  65518. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  65519. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  65520. var parsedCamera = parsedData.cameras[index];
  65521. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  65522. container.cameras.push(camera);
  65523. log += (index === 0 ? "\n\tCameras:" : "");
  65524. log += "\n\t\t" + camera.toString(fullDetails);
  65525. }
  65526. }
  65527. // Browsing all the graph to connect the dots
  65528. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  65529. var camera = scene.cameras[index];
  65530. if (camera._waitingParentId) {
  65531. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  65532. camera._waitingParentId = null;
  65533. }
  65534. }
  65535. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  65536. var light_1 = scene.lights[index];
  65537. if (light_1 && light_1._waitingParentId) {
  65538. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  65539. light_1._waitingParentId = null;
  65540. }
  65541. }
  65542. // Sounds
  65543. // TODO: add sound
  65544. var loadedSounds = [];
  65545. var loadedSound;
  65546. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  65547. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  65548. var parsedSound = parsedData.sounds[index];
  65549. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  65550. if (!parsedSound.url)
  65551. parsedSound.url = parsedSound.name;
  65552. if (!loadedSounds[parsedSound.url]) {
  65553. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  65554. loadedSounds[parsedSound.url] = loadedSound;
  65555. container.sounds.push(loadedSound);
  65556. }
  65557. else {
  65558. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  65559. }
  65560. }
  65561. else {
  65562. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  65563. }
  65564. }
  65565. }
  65566. loadedSounds = [];
  65567. // Connect parents & children and parse actions
  65568. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  65569. var transformNode = scene.transformNodes[index];
  65570. if (transformNode._waitingParentId) {
  65571. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  65572. transformNode._waitingParentId = null;
  65573. }
  65574. }
  65575. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  65576. var mesh = scene.meshes[index];
  65577. if (mesh._waitingParentId) {
  65578. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  65579. mesh._waitingParentId = null;
  65580. }
  65581. if (mesh._waitingActions) {
  65582. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  65583. mesh._waitingActions = null;
  65584. }
  65585. }
  65586. // freeze world matrix application
  65587. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  65588. var currentMesh = scene.meshes[index];
  65589. if (currentMesh._waitingFreezeWorldMatrix) {
  65590. currentMesh.freezeWorldMatrix();
  65591. currentMesh._waitingFreezeWorldMatrix = null;
  65592. }
  65593. else {
  65594. currentMesh.computeWorldMatrix(true);
  65595. }
  65596. }
  65597. // Particles Systems
  65598. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  65599. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  65600. var parsedParticleSystem = parsedData.particleSystems[index];
  65601. if (parsedParticleSystem.activeParticleCount) {
  65602. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  65603. container.particleSystems.push(ps);
  65604. }
  65605. else {
  65606. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  65607. container.particleSystems.push(ps);
  65608. }
  65609. }
  65610. }
  65611. // Lens flares
  65612. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  65613. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  65614. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  65615. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  65616. container.lensFlareSystems.push(lf);
  65617. }
  65618. }
  65619. // Shadows
  65620. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  65621. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  65622. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  65623. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  65624. container.shadowGenerators.push(sg);
  65625. }
  65626. }
  65627. // Lights exclusions / inclusions
  65628. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  65629. var light_2 = scene.lights[index];
  65630. // Excluded check
  65631. if (light_2._excludedMeshesIds.length > 0) {
  65632. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  65633. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  65634. if (excludedMesh) {
  65635. light_2.excludedMeshes.push(excludedMesh);
  65636. }
  65637. }
  65638. light_2._excludedMeshesIds = [];
  65639. }
  65640. // Included check
  65641. if (light_2._includedOnlyMeshesIds.length > 0) {
  65642. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  65643. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  65644. if (includedOnlyMesh) {
  65645. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  65646. }
  65647. }
  65648. light_2._includedOnlyMeshesIds = [];
  65649. }
  65650. }
  65651. // Actions (scene)
  65652. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  65653. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  65654. }
  65655. if (!addToScene) {
  65656. container.removeAllFromScene();
  65657. }
  65658. }
  65659. catch (err) {
  65660. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  65661. if (onError) {
  65662. onError(msg, err);
  65663. }
  65664. else {
  65665. BABYLON.Tools.Log(msg);
  65666. throw err;
  65667. }
  65668. }
  65669. finally {
  65670. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  65671. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  65672. }
  65673. }
  65674. return container;
  65675. };
  65676. BABYLON.SceneLoader.RegisterPlugin({
  65677. name: "babylon.js",
  65678. extensions: ".babylon",
  65679. canDirectLoad: function (data) {
  65680. if (data.indexOf("babylon") !== -1) {
  65681. return true;
  65682. }
  65683. return false;
  65684. },
  65685. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  65686. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  65687. // when SceneLoader.debugLogging = true (default), or exception encountered.
  65688. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  65689. // and avoid problems with multiple concurrent .babylon loads.
  65690. var log = "importMesh has failed JSON parse";
  65691. try {
  65692. var parsedData = JSON.parse(data);
  65693. log = "";
  65694. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  65695. if (!meshesNames) {
  65696. meshesNames = null;
  65697. }
  65698. else if (!Array.isArray(meshesNames)) {
  65699. meshesNames = [meshesNames];
  65700. }
  65701. var hierarchyIds = new Array();
  65702. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  65703. var loadedSkeletonsIds = [];
  65704. var loadedMaterialsIds = [];
  65705. var index;
  65706. var cache;
  65707. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  65708. var parsedMesh = parsedData.meshes[index];
  65709. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  65710. if (meshesNames !== null) {
  65711. // Remove found mesh name from list.
  65712. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  65713. }
  65714. //Geometry?
  65715. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  65716. //does the file contain geometries?
  65717. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  65718. //find the correct geometry and add it to the scene
  65719. var found = false;
  65720. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  65721. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  65722. return;
  65723. }
  65724. else {
  65725. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  65726. if (parsedGeometryData.id === parsedMesh.geometryId) {
  65727. switch (geometryType) {
  65728. case "boxes":
  65729. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  65730. break;
  65731. case "spheres":
  65732. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  65733. break;
  65734. case "cylinders":
  65735. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  65736. break;
  65737. case "toruses":
  65738. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  65739. break;
  65740. case "grounds":
  65741. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  65742. break;
  65743. case "planes":
  65744. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  65745. break;
  65746. case "torusKnots":
  65747. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  65748. break;
  65749. case "vertexData":
  65750. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  65751. break;
  65752. }
  65753. found = true;
  65754. }
  65755. });
  65756. }
  65757. });
  65758. if (found === false) {
  65759. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  65760. }
  65761. }
  65762. }
  65763. // Material ?
  65764. if (parsedMesh.materialId) {
  65765. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  65766. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  65767. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  65768. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  65769. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  65770. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  65771. var subMatId = parsedMultiMaterial.materials[matIndex];
  65772. loadedMaterialsIds.push(subMatId);
  65773. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  65774. if (mat) {
  65775. log += "\n\tMaterial " + mat.toString(fullDetails);
  65776. }
  65777. }
  65778. loadedMaterialsIds.push(parsedMultiMaterial.id);
  65779. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  65780. if (mmat) {
  65781. materialFound = true;
  65782. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  65783. }
  65784. break;
  65785. }
  65786. }
  65787. }
  65788. if (materialFound === false) {
  65789. loadedMaterialsIds.push(parsedMesh.materialId);
  65790. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  65791. if (!mat) {
  65792. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  65793. }
  65794. else {
  65795. log += "\n\tMaterial " + mat.toString(fullDetails);
  65796. }
  65797. }
  65798. }
  65799. // Skeleton ?
  65800. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  65801. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  65802. if (skeletonAlreadyLoaded === false) {
  65803. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  65804. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  65805. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  65806. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  65807. skeletons.push(skeleton);
  65808. loadedSkeletonsIds.push(parsedSkeleton.id);
  65809. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  65810. }
  65811. }
  65812. }
  65813. }
  65814. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  65815. meshes.push(mesh);
  65816. log += "\n\tMesh " + mesh.toString(fullDetails);
  65817. }
  65818. }
  65819. // Connecting parents
  65820. var currentMesh;
  65821. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  65822. currentMesh = scene.meshes[index];
  65823. if (currentMesh._waitingParentId) {
  65824. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  65825. currentMesh._waitingParentId = null;
  65826. }
  65827. }
  65828. // freeze and compute world matrix application
  65829. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  65830. currentMesh = scene.meshes[index];
  65831. if (currentMesh._waitingFreezeWorldMatrix) {
  65832. currentMesh.freezeWorldMatrix();
  65833. currentMesh._waitingFreezeWorldMatrix = null;
  65834. }
  65835. else {
  65836. currentMesh.computeWorldMatrix(true);
  65837. }
  65838. }
  65839. }
  65840. // Particles
  65841. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  65842. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  65843. var parsedParticleSystem = parsedData.particleSystems[index];
  65844. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  65845. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  65846. }
  65847. }
  65848. }
  65849. return true;
  65850. }
  65851. catch (err) {
  65852. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  65853. if (onError) {
  65854. onError(msg, err);
  65855. }
  65856. else {
  65857. BABYLON.Tools.Log(msg);
  65858. throw err;
  65859. }
  65860. }
  65861. finally {
  65862. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  65863. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  65864. }
  65865. }
  65866. return false;
  65867. },
  65868. load: function (scene, data, rootUrl, onError) {
  65869. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  65870. // when SceneLoader.debugLogging = true (default), or exception encountered.
  65871. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  65872. // and avoid problems with multiple concurrent .babylon loads.
  65873. var log = "importScene has failed JSON parse";
  65874. try {
  65875. var parsedData = JSON.parse(data);
  65876. log = "";
  65877. // Scene
  65878. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  65879. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  65880. }
  65881. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  65882. scene.autoClear = parsedData.autoClear;
  65883. }
  65884. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  65885. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  65886. }
  65887. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  65888. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  65889. }
  65890. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  65891. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  65892. }
  65893. // Fog
  65894. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  65895. scene.fogMode = parsedData.fogMode;
  65896. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  65897. scene.fogStart = parsedData.fogStart;
  65898. scene.fogEnd = parsedData.fogEnd;
  65899. scene.fogDensity = parsedData.fogDensity;
  65900. log += "\tFog mode for scene: ";
  65901. switch (scene.fogMode) {
  65902. // getters not compiling, so using hardcoded
  65903. case 1:
  65904. log += "exp\n";
  65905. break;
  65906. case 2:
  65907. log += "exp2\n";
  65908. break;
  65909. case 3:
  65910. log += "linear\n";
  65911. break;
  65912. }
  65913. }
  65914. //Physics
  65915. if (parsedData.physicsEnabled) {
  65916. var physicsPlugin;
  65917. if (parsedData.physicsEngine === "cannon") {
  65918. physicsPlugin = new BABYLON.CannonJSPlugin();
  65919. }
  65920. else if (parsedData.physicsEngine === "oimo") {
  65921. physicsPlugin = new BABYLON.OimoJSPlugin();
  65922. }
  65923. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  65924. //else - default engine, which is currently oimo
  65925. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  65926. scene.enablePhysics(physicsGravity, physicsPlugin);
  65927. }
  65928. // Metadata
  65929. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  65930. scene.metadata = parsedData.metadata;
  65931. }
  65932. //collisions, if defined. otherwise, default is true
  65933. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  65934. scene.collisionsEnabled = parsedData.collisionsEnabled;
  65935. }
  65936. scene.workerCollisions = !!parsedData.workerCollisions;
  65937. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  65938. if (!container) {
  65939. return false;
  65940. }
  65941. if (parsedData.autoAnimate) {
  65942. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  65943. }
  65944. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  65945. scene.setActiveCameraByID(parsedData.activeCameraID);
  65946. }
  65947. // Environment texture
  65948. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  65949. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  65950. if (parsedData.createDefaultSkybox === true) {
  65951. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  65952. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  65953. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  65954. }
  65955. }
  65956. // Finish
  65957. return true;
  65958. }
  65959. catch (err) {
  65960. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  65961. if (onError) {
  65962. onError(msg, err);
  65963. }
  65964. else {
  65965. BABYLON.Tools.Log(msg);
  65966. throw err;
  65967. }
  65968. }
  65969. finally {
  65970. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  65971. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  65972. }
  65973. }
  65974. return false;
  65975. },
  65976. loadAssetContainer: function (scene, data, rootUrl, onError) {
  65977. var container = loadAssetContainer(scene, data, rootUrl, onError);
  65978. return container;
  65979. }
  65980. });
  65981. })(BABYLON || (BABYLON = {}));
  65982. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  65983. "use strict";
  65984. var BABYLON;
  65985. (function (BABYLON) {
  65986. var FilesInput = /** @class */ (function () {
  65987. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  65988. this.onProcessFileCallback = function () { return true; };
  65989. this._engine = engine;
  65990. this._currentScene = scene;
  65991. this._sceneLoadedCallback = sceneLoadedCallback;
  65992. this._progressCallback = progressCallback;
  65993. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  65994. this._textureLoadingCallback = textureLoadingCallback;
  65995. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  65996. this._onReloadCallback = onReloadCallback;
  65997. this._errorCallback = errorCallback;
  65998. }
  65999. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  66000. var _this = this;
  66001. if (elementToMonitor) {
  66002. this._elementToMonitor = elementToMonitor;
  66003. this._dragEnterHandler = function (e) { _this.drag(e); };
  66004. this._dragOverHandler = function (e) { _this.drag(e); };
  66005. this._dropHandler = function (e) { _this.drop(e); };
  66006. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  66007. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  66008. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  66009. }
  66010. };
  66011. FilesInput.prototype.dispose = function () {
  66012. if (!this._elementToMonitor) {
  66013. return;
  66014. }
  66015. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  66016. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  66017. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  66018. };
  66019. FilesInput.prototype.renderFunction = function () {
  66020. if (this._additionalRenderLoopLogicCallback) {
  66021. this._additionalRenderLoopLogicCallback();
  66022. }
  66023. if (this._currentScene) {
  66024. if (this._textureLoadingCallback) {
  66025. var remaining = this._currentScene.getWaitingItemsCount();
  66026. if (remaining > 0) {
  66027. this._textureLoadingCallback(remaining);
  66028. }
  66029. }
  66030. this._currentScene.render();
  66031. }
  66032. };
  66033. FilesInput.prototype.drag = function (e) {
  66034. e.stopPropagation();
  66035. e.preventDefault();
  66036. };
  66037. FilesInput.prototype.drop = function (eventDrop) {
  66038. eventDrop.stopPropagation();
  66039. eventDrop.preventDefault();
  66040. this.loadFiles(eventDrop);
  66041. };
  66042. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  66043. var _this = this;
  66044. var reader = folder.createReader();
  66045. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  66046. reader.readEntries(function (entries) {
  66047. remaining.count += entries.length;
  66048. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  66049. var entry = entries_1[_i];
  66050. if (entry.isFile) {
  66051. entry.file(function (file) {
  66052. file.correctName = relativePath + file.name;
  66053. files.push(file);
  66054. if (--remaining.count === 0) {
  66055. callback();
  66056. }
  66057. });
  66058. }
  66059. else if (entry.isDirectory) {
  66060. _this._traverseFolder(entry, files, remaining, callback);
  66061. }
  66062. }
  66063. if (--remaining.count) {
  66064. callback();
  66065. }
  66066. });
  66067. };
  66068. FilesInput.prototype._processFiles = function (files) {
  66069. for (var i = 0; i < files.length; i++) {
  66070. var name = files[i].correctName.toLowerCase();
  66071. var extension = name.split('.').pop();
  66072. if (!this.onProcessFileCallback(files[i], name, extension)) {
  66073. continue;
  66074. }
  66075. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  66076. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  66077. this._sceneFileToLoad = files[i];
  66078. }
  66079. else {
  66080. FilesInput.FilesToLoad[name] = files[i];
  66081. }
  66082. }
  66083. };
  66084. FilesInput.prototype.loadFiles = function (event) {
  66085. var _this = this;
  66086. if (this._startingProcessingFilesCallback)
  66087. this._startingProcessingFilesCallback();
  66088. // Handling data transfer via drag'n'drop
  66089. if (event && event.dataTransfer && event.dataTransfer.files) {
  66090. this._filesToLoad = event.dataTransfer.files;
  66091. }
  66092. // Handling files from input files
  66093. if (event && event.target && event.target.files) {
  66094. this._filesToLoad = event.target.files;
  66095. }
  66096. if (this._filesToLoad && this._filesToLoad.length > 0) {
  66097. var files_1 = new Array();
  66098. var folders = [];
  66099. var items = event.dataTransfer ? event.dataTransfer.items : null;
  66100. for (var i = 0; i < this._filesToLoad.length; i++) {
  66101. var fileToLoad = this._filesToLoad[i];
  66102. var name_1 = fileToLoad.name.toLowerCase();
  66103. var entry = void 0;
  66104. fileToLoad.correctName = name_1;
  66105. if (items) {
  66106. var item = items[i];
  66107. if (item.getAsEntry) {
  66108. entry = item.getAsEntry();
  66109. }
  66110. else if (item.webkitGetAsEntry) {
  66111. entry = item.webkitGetAsEntry();
  66112. }
  66113. }
  66114. if (!entry) {
  66115. files_1.push(fileToLoad);
  66116. }
  66117. else {
  66118. if (entry.isDirectory) {
  66119. folders.push(entry);
  66120. }
  66121. else {
  66122. files_1.push(fileToLoad);
  66123. }
  66124. }
  66125. }
  66126. if (folders.length === 0) {
  66127. this._processFiles(files_1);
  66128. this._processReload();
  66129. }
  66130. else {
  66131. var remaining = { count: folders.length };
  66132. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  66133. var folder = folders_1[_i];
  66134. this._traverseFolder(folder, files_1, remaining, function () {
  66135. _this._processFiles(files_1);
  66136. if (remaining.count === 0) {
  66137. _this._processReload();
  66138. }
  66139. });
  66140. }
  66141. }
  66142. }
  66143. };
  66144. FilesInput.prototype._processReload = function () {
  66145. if (this._onReloadCallback) {
  66146. this._onReloadCallback(this._sceneFileToLoad);
  66147. }
  66148. else {
  66149. this.reload();
  66150. }
  66151. };
  66152. FilesInput.prototype.reload = function () {
  66153. var _this = this;
  66154. // If a scene file has been provided
  66155. if (this._sceneFileToLoad) {
  66156. if (this._currentScene) {
  66157. if (BABYLON.Tools.errorsCount > 0) {
  66158. BABYLON.Tools.ClearLogCache();
  66159. }
  66160. this._engine.stopRenderLoop();
  66161. this._currentScene.dispose();
  66162. }
  66163. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  66164. if (_this._progressCallback) {
  66165. _this._progressCallback(progress);
  66166. }
  66167. }).then(function (scene) {
  66168. _this._currentScene = scene;
  66169. if (_this._sceneLoadedCallback) {
  66170. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  66171. }
  66172. // Wait for textures and shaders to be ready
  66173. _this._currentScene.executeWhenReady(function () {
  66174. _this._engine.runRenderLoop(function () {
  66175. _this.renderFunction();
  66176. });
  66177. });
  66178. }).catch(function (error) {
  66179. if (_this._errorCallback) {
  66180. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  66181. }
  66182. });
  66183. }
  66184. else {
  66185. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  66186. }
  66187. };
  66188. FilesInput.FilesToLoad = {};
  66189. return FilesInput;
  66190. }());
  66191. BABYLON.FilesInput = FilesInput;
  66192. })(BABYLON || (BABYLON = {}));
  66193. //# sourceMappingURL=babylon.filesInput.js.map
  66194. "use strict";
  66195. var BABYLON;
  66196. (function (BABYLON) {
  66197. /**
  66198. * This class implement a typical dictionary using a string as key and the generic type T as value.
  66199. * The underlying implementation relies on an associative array to ensure the best performances.
  66200. * The value can be anything including 'null' but except 'undefined'
  66201. */
  66202. var StringDictionary = /** @class */ (function () {
  66203. function StringDictionary() {
  66204. this._count = 0;
  66205. this._data = {};
  66206. }
  66207. /**
  66208. * This will clear this dictionary and copy the content from the 'source' one.
  66209. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  66210. * @param source the dictionary to take the content from and copy to this dictionary
  66211. */
  66212. StringDictionary.prototype.copyFrom = function (source) {
  66213. var _this = this;
  66214. this.clear();
  66215. source.forEach(function (t, v) { return _this.add(t, v); });
  66216. };
  66217. /**
  66218. * Get a value based from its key
  66219. * @param key the given key to get the matching value from
  66220. * @return the value if found, otherwise undefined is returned
  66221. */
  66222. StringDictionary.prototype.get = function (key) {
  66223. var val = this._data[key];
  66224. if (val !== undefined) {
  66225. return val;
  66226. }
  66227. return undefined;
  66228. };
  66229. /**
  66230. * Get a value from its key or add it if it doesn't exist.
  66231. * This method will ensure you that a given key/data will be present in the dictionary.
  66232. * @param key the given key to get the matching value from
  66233. * @param factory the factory that will create the value if the key is not present in the dictionary.
  66234. * The factory will only be invoked if there's no data for the given key.
  66235. * @return the value corresponding to the key.
  66236. */
  66237. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  66238. var val = this.get(key);
  66239. if (val !== undefined) {
  66240. return val;
  66241. }
  66242. val = factory(key);
  66243. if (val) {
  66244. this.add(key, val);
  66245. }
  66246. return val;
  66247. };
  66248. /**
  66249. * Get a value from its key if present in the dictionary otherwise add it
  66250. * @param key the key to get the value from
  66251. * @param val if there's no such key/value pair in the dictionary add it with this value
  66252. * @return the value corresponding to the key
  66253. */
  66254. StringDictionary.prototype.getOrAdd = function (key, val) {
  66255. var curVal = this.get(key);
  66256. if (curVal !== undefined) {
  66257. return curVal;
  66258. }
  66259. this.add(key, val);
  66260. return val;
  66261. };
  66262. /**
  66263. * Check if there's a given key in the dictionary
  66264. * @param key the key to check for
  66265. * @return true if the key is present, false otherwise
  66266. */
  66267. StringDictionary.prototype.contains = function (key) {
  66268. return this._data[key] !== undefined;
  66269. };
  66270. /**
  66271. * Add a new key and its corresponding value
  66272. * @param key the key to add
  66273. * @param value the value corresponding to the key
  66274. * @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
  66275. */
  66276. StringDictionary.prototype.add = function (key, value) {
  66277. if (this._data[key] !== undefined) {
  66278. return false;
  66279. }
  66280. this._data[key] = value;
  66281. ++this._count;
  66282. return true;
  66283. };
  66284. StringDictionary.prototype.set = function (key, value) {
  66285. if (this._data[key] === undefined) {
  66286. return false;
  66287. }
  66288. this._data[key] = value;
  66289. return true;
  66290. };
  66291. /**
  66292. * Get the element of the given key and remove it from the dictionary
  66293. * @param key
  66294. */
  66295. StringDictionary.prototype.getAndRemove = function (key) {
  66296. var val = this.get(key);
  66297. if (val !== undefined) {
  66298. delete this._data[key];
  66299. --this._count;
  66300. return val;
  66301. }
  66302. return null;
  66303. };
  66304. /**
  66305. * Remove a key/value from the dictionary.
  66306. * @param key the key to remove
  66307. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  66308. */
  66309. StringDictionary.prototype.remove = function (key) {
  66310. if (this.contains(key)) {
  66311. delete this._data[key];
  66312. --this._count;
  66313. return true;
  66314. }
  66315. return false;
  66316. };
  66317. /**
  66318. * Clear the whole content of the dictionary
  66319. */
  66320. StringDictionary.prototype.clear = function () {
  66321. this._data = {};
  66322. this._count = 0;
  66323. };
  66324. Object.defineProperty(StringDictionary.prototype, "count", {
  66325. get: function () {
  66326. return this._count;
  66327. },
  66328. enumerable: true,
  66329. configurable: true
  66330. });
  66331. /**
  66332. * Execute a callback on each key/val of the dictionary.
  66333. * Note that you can remove any element in this dictionary in the callback implementation
  66334. * @param callback the callback to execute on a given key/value pair
  66335. */
  66336. StringDictionary.prototype.forEach = function (callback) {
  66337. for (var cur in this._data) {
  66338. var val = this._data[cur];
  66339. callback(cur, val);
  66340. }
  66341. };
  66342. /**
  66343. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  66344. * If the callback returns null or undefined the method will iterate to the next key/value pair
  66345. * Note that you can remove any element in this dictionary in the callback implementation
  66346. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  66347. */
  66348. StringDictionary.prototype.first = function (callback) {
  66349. for (var cur in this._data) {
  66350. var val = this._data[cur];
  66351. var res = callback(cur, val);
  66352. if (res) {
  66353. return res;
  66354. }
  66355. }
  66356. return null;
  66357. };
  66358. return StringDictionary;
  66359. }());
  66360. BABYLON.StringDictionary = StringDictionary;
  66361. })(BABYLON || (BABYLON = {}));
  66362. //# sourceMappingURL=babylon.stringDictionary.js.map
  66363. "use strict";
  66364. var BABYLON;
  66365. (function (BABYLON) {
  66366. var Tags = /** @class */ (function () {
  66367. function Tags() {
  66368. }
  66369. Tags.EnableFor = function (obj) {
  66370. obj._tags = obj._tags || {};
  66371. obj.hasTags = function () {
  66372. return Tags.HasTags(obj);
  66373. };
  66374. obj.addTags = function (tagsString) {
  66375. return Tags.AddTagsTo(obj, tagsString);
  66376. };
  66377. obj.removeTags = function (tagsString) {
  66378. return Tags.RemoveTagsFrom(obj, tagsString);
  66379. };
  66380. obj.matchesTagsQuery = function (tagsQuery) {
  66381. return Tags.MatchesQuery(obj, tagsQuery);
  66382. };
  66383. };
  66384. Tags.DisableFor = function (obj) {
  66385. delete obj._tags;
  66386. delete obj.hasTags;
  66387. delete obj.addTags;
  66388. delete obj.removeTags;
  66389. delete obj.matchesTagsQuery;
  66390. };
  66391. Tags.HasTags = function (obj) {
  66392. if (!obj._tags) {
  66393. return false;
  66394. }
  66395. return !BABYLON.Tools.IsEmpty(obj._tags);
  66396. };
  66397. Tags.GetTags = function (obj, asString) {
  66398. if (asString === void 0) { asString = true; }
  66399. if (!obj._tags) {
  66400. return null;
  66401. }
  66402. if (asString) {
  66403. var tagsArray = [];
  66404. for (var tag in obj._tags) {
  66405. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  66406. tagsArray.push(tag);
  66407. }
  66408. }
  66409. return tagsArray.join(" ");
  66410. }
  66411. else {
  66412. return obj._tags;
  66413. }
  66414. };
  66415. // the tags 'true' and 'false' are reserved and cannot be used as tags
  66416. // a tag cannot start with '||', '&&', and '!'
  66417. // it cannot contain whitespaces
  66418. Tags.AddTagsTo = function (obj, tagsString) {
  66419. if (!tagsString) {
  66420. return;
  66421. }
  66422. if (typeof tagsString !== "string") {
  66423. return;
  66424. }
  66425. var tags = tagsString.split(" ");
  66426. tags.forEach(function (tag, index, array) {
  66427. Tags._AddTagTo(obj, tag);
  66428. });
  66429. };
  66430. Tags._AddTagTo = function (obj, tag) {
  66431. tag = tag.trim();
  66432. if (tag === "" || tag === "true" || tag === "false") {
  66433. return;
  66434. }
  66435. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  66436. return;
  66437. }
  66438. Tags.EnableFor(obj);
  66439. obj._tags[tag] = true;
  66440. };
  66441. Tags.RemoveTagsFrom = function (obj, tagsString) {
  66442. if (!Tags.HasTags(obj)) {
  66443. return;
  66444. }
  66445. var tags = tagsString.split(" ");
  66446. for (var t in tags) {
  66447. Tags._RemoveTagFrom(obj, tags[t]);
  66448. }
  66449. };
  66450. Tags._RemoveTagFrom = function (obj, tag) {
  66451. delete obj._tags[tag];
  66452. };
  66453. Tags.MatchesQuery = function (obj, tagsQuery) {
  66454. if (tagsQuery === undefined) {
  66455. return true;
  66456. }
  66457. if (tagsQuery === "") {
  66458. return Tags.HasTags(obj);
  66459. }
  66460. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  66461. };
  66462. return Tags;
  66463. }());
  66464. BABYLON.Tags = Tags;
  66465. })(BABYLON || (BABYLON = {}));
  66466. //# sourceMappingURL=babylon.tags.js.map
  66467. "use strict";
  66468. var BABYLON;
  66469. (function (BABYLON) {
  66470. var AndOrNotEvaluator = /** @class */ (function () {
  66471. function AndOrNotEvaluator() {
  66472. }
  66473. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  66474. if (!query.match(/\([^\(\)]*\)/g)) {
  66475. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  66476. }
  66477. else {
  66478. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  66479. // remove parenthesis
  66480. r = r.slice(1, r.length - 1);
  66481. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  66482. });
  66483. }
  66484. if (query === "true") {
  66485. return true;
  66486. }
  66487. if (query === "false") {
  66488. return false;
  66489. }
  66490. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  66491. };
  66492. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  66493. evaluateCallback = evaluateCallback || (function (r) {
  66494. return r === "true" ? true : false;
  66495. });
  66496. var result;
  66497. var or = parenthesisContent.split("||");
  66498. for (var i in or) {
  66499. if (or.hasOwnProperty(i)) {
  66500. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  66501. var and = ori.split("&&");
  66502. if (and.length > 1) {
  66503. for (var j = 0; j < and.length; ++j) {
  66504. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  66505. if (andj !== "true" && andj !== "false") {
  66506. if (andj[0] === "!") {
  66507. result = !evaluateCallback(andj.substring(1));
  66508. }
  66509. else {
  66510. result = evaluateCallback(andj);
  66511. }
  66512. }
  66513. else {
  66514. result = andj === "true" ? true : false;
  66515. }
  66516. if (!result) {
  66517. ori = "false";
  66518. break;
  66519. }
  66520. }
  66521. }
  66522. if (result || ori === "true") {
  66523. result = true;
  66524. break;
  66525. }
  66526. // result equals false (or undefined)
  66527. if (ori !== "true" && ori !== "false") {
  66528. if (ori[0] === "!") {
  66529. result = !evaluateCallback(ori.substring(1));
  66530. }
  66531. else {
  66532. result = evaluateCallback(ori);
  66533. }
  66534. }
  66535. else {
  66536. result = ori === "true" ? true : false;
  66537. }
  66538. }
  66539. }
  66540. // the whole parenthesis scope is replaced by 'true' or 'false'
  66541. return result ? "true" : "false";
  66542. };
  66543. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  66544. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  66545. // remove whitespaces
  66546. r = r.replace(/[\s]/g, function () { return ""; });
  66547. return r.length % 2 ? "!" : "";
  66548. });
  66549. booleanString = booleanString.trim();
  66550. if (booleanString === "!true") {
  66551. booleanString = "false";
  66552. }
  66553. else if (booleanString === "!false") {
  66554. booleanString = "true";
  66555. }
  66556. return booleanString;
  66557. };
  66558. return AndOrNotEvaluator;
  66559. }());
  66560. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  66561. })(BABYLON || (BABYLON = {}));
  66562. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  66563. "use strict";
  66564. var BABYLON;
  66565. (function (BABYLON) {
  66566. var Database = /** @class */ (function () {
  66567. function Database(urlToScene, callbackManifestChecked) {
  66568. // Handling various flavors of prefixed version of IndexedDB
  66569. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  66570. this.callbackManifestChecked = callbackManifestChecked;
  66571. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  66572. this.db = null;
  66573. this._enableSceneOffline = false;
  66574. this._enableTexturesOffline = false;
  66575. this.manifestVersionFound = 0;
  66576. this.mustUpdateRessources = false;
  66577. this.hasReachedQuota = false;
  66578. if (!Database.IDBStorageEnabled) {
  66579. this.callbackManifestChecked(true);
  66580. }
  66581. else {
  66582. this.checkManifestFile();
  66583. }
  66584. }
  66585. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  66586. get: function () {
  66587. return this._enableSceneOffline;
  66588. },
  66589. enumerable: true,
  66590. configurable: true
  66591. });
  66592. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  66593. get: function () {
  66594. return this._enableTexturesOffline;
  66595. },
  66596. enumerable: true,
  66597. configurable: true
  66598. });
  66599. Database.prototype.checkManifestFile = function () {
  66600. var _this = this;
  66601. var noManifestFile = function () {
  66602. _this._enableSceneOffline = false;
  66603. _this._enableTexturesOffline = false;
  66604. _this.callbackManifestChecked(false);
  66605. };
  66606. var timeStampUsed = false;
  66607. var manifestURL = this.currentSceneUrl + ".manifest";
  66608. var xhr = new XMLHttpRequest();
  66609. if (navigator.onLine) {
  66610. // Adding a timestamp to by-pass browsers' cache
  66611. timeStampUsed = true;
  66612. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  66613. }
  66614. xhr.open("GET", manifestURL, true);
  66615. xhr.addEventListener("load", function () {
  66616. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  66617. try {
  66618. var manifestFile = JSON.parse(xhr.response);
  66619. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  66620. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  66621. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  66622. _this.manifestVersionFound = manifestFile.version;
  66623. }
  66624. if (_this.callbackManifestChecked) {
  66625. _this.callbackManifestChecked(true);
  66626. }
  66627. }
  66628. catch (ex) {
  66629. noManifestFile();
  66630. }
  66631. }
  66632. else {
  66633. noManifestFile();
  66634. }
  66635. }, false);
  66636. xhr.addEventListener("error", function (event) {
  66637. if (timeStampUsed) {
  66638. timeStampUsed = false;
  66639. // Let's retry without the timeStamp
  66640. // It could fail when coupled with HTML5 Offline API
  66641. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  66642. xhr.open("GET", retryManifestURL, true);
  66643. xhr.send();
  66644. }
  66645. else {
  66646. noManifestFile();
  66647. }
  66648. }, false);
  66649. try {
  66650. xhr.send();
  66651. }
  66652. catch (ex) {
  66653. BABYLON.Tools.Error("Error on XHR send request.");
  66654. this.callbackManifestChecked(false);
  66655. }
  66656. };
  66657. Database.prototype.openAsync = function (successCallback, errorCallback) {
  66658. var _this = this;
  66659. var handleError = function () {
  66660. _this.isSupported = false;
  66661. if (errorCallback)
  66662. errorCallback();
  66663. };
  66664. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  66665. // Your browser doesn't support IndexedDB
  66666. this.isSupported = false;
  66667. if (errorCallback)
  66668. errorCallback();
  66669. }
  66670. else {
  66671. // If the DB hasn't been opened or created yet
  66672. if (!this.db) {
  66673. this.hasReachedQuota = false;
  66674. this.isSupported = true;
  66675. var request = this.idbFactory.open("babylonjs", 1);
  66676. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  66677. request.onerror = function (event) {
  66678. handleError();
  66679. };
  66680. // executes when a version change transaction cannot complete due to other active transactions
  66681. request.onblocked = function (event) {
  66682. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  66683. handleError();
  66684. };
  66685. // DB has been opened successfully
  66686. request.onsuccess = function (event) {
  66687. _this.db = request.result;
  66688. successCallback();
  66689. };
  66690. // Initialization of the DB. Creating Scenes & Textures stores
  66691. request.onupgradeneeded = function (event) {
  66692. _this.db = (event.target).result;
  66693. if (_this.db) {
  66694. try {
  66695. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  66696. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  66697. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  66698. }
  66699. catch (ex) {
  66700. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  66701. handleError();
  66702. }
  66703. }
  66704. };
  66705. }
  66706. else {
  66707. if (successCallback)
  66708. successCallback();
  66709. }
  66710. }
  66711. };
  66712. Database.prototype.loadImageFromDB = function (url, image) {
  66713. var _this = this;
  66714. var completeURL = Database.ReturnFullUrlLocation(url);
  66715. var saveAndLoadImage = function () {
  66716. if (!_this.hasReachedQuota && _this.db !== null) {
  66717. // the texture is not yet in the DB, let's try to save it
  66718. _this._saveImageIntoDBAsync(completeURL, image);
  66719. }
  66720. else {
  66721. image.src = url;
  66722. }
  66723. };
  66724. if (!this.mustUpdateRessources) {
  66725. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  66726. }
  66727. else {
  66728. saveAndLoadImage();
  66729. }
  66730. };
  66731. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  66732. if (this.isSupported && this.db !== null) {
  66733. var texture;
  66734. var transaction = this.db.transaction(["textures"]);
  66735. transaction.onabort = function (event) {
  66736. image.src = url;
  66737. };
  66738. transaction.oncomplete = function (event) {
  66739. var blobTextureURL;
  66740. if (texture) {
  66741. var URL = window.URL || window.webkitURL;
  66742. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  66743. image.onerror = function () {
  66744. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  66745. image.src = url;
  66746. };
  66747. image.src = blobTextureURL;
  66748. }
  66749. else {
  66750. notInDBCallback();
  66751. }
  66752. };
  66753. var getRequest = transaction.objectStore("textures").get(url);
  66754. getRequest.onsuccess = function (event) {
  66755. texture = (event.target).result;
  66756. };
  66757. getRequest.onerror = function (event) {
  66758. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  66759. image.src = url;
  66760. };
  66761. }
  66762. else {
  66763. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  66764. image.src = url;
  66765. }
  66766. };
  66767. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  66768. var _this = this;
  66769. if (this.isSupported) {
  66770. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  66771. var generateBlobUrl = function () {
  66772. var blobTextureURL;
  66773. if (blob) {
  66774. var URL = window.URL || window.webkitURL;
  66775. try {
  66776. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  66777. }
  66778. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  66779. catch (ex) {
  66780. blobTextureURL = URL.createObjectURL(blob);
  66781. }
  66782. }
  66783. if (blobTextureURL) {
  66784. image.src = blobTextureURL;
  66785. }
  66786. };
  66787. if (Database.IsUASupportingBlobStorage) {
  66788. var xhr = new XMLHttpRequest(), blob;
  66789. xhr.open("GET", url, true);
  66790. xhr.responseType = "blob";
  66791. xhr.addEventListener("load", function () {
  66792. if (xhr.status === 200 && _this.db) {
  66793. // Blob as response (XHR2)
  66794. blob = xhr.response;
  66795. var transaction = _this.db.transaction(["textures"], "readwrite");
  66796. // the transaction could abort because of a QuotaExceededError error
  66797. transaction.onabort = function (event) {
  66798. try {
  66799. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  66800. var srcElement = (event.srcElement || event.target);
  66801. var error = srcElement.error;
  66802. if (error && error.name === "QuotaExceededError") {
  66803. _this.hasReachedQuota = true;
  66804. }
  66805. }
  66806. catch (ex) { }
  66807. generateBlobUrl();
  66808. };
  66809. transaction.oncomplete = function (event) {
  66810. generateBlobUrl();
  66811. };
  66812. var newTexture = { textureUrl: url, data: blob };
  66813. try {
  66814. // Put the blob into the dabase
  66815. var addRequest = transaction.objectStore("textures").put(newTexture);
  66816. addRequest.onsuccess = function (event) {
  66817. };
  66818. addRequest.onerror = function (event) {
  66819. generateBlobUrl();
  66820. };
  66821. }
  66822. catch (ex) {
  66823. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  66824. if (ex.code === 25) {
  66825. Database.IsUASupportingBlobStorage = false;
  66826. }
  66827. image.src = url;
  66828. }
  66829. }
  66830. else {
  66831. image.src = url;
  66832. }
  66833. }, false);
  66834. xhr.addEventListener("error", function (event) {
  66835. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  66836. image.src = url;
  66837. }, false);
  66838. xhr.send();
  66839. }
  66840. else {
  66841. image.src = url;
  66842. }
  66843. }
  66844. else {
  66845. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  66846. image.src = url;
  66847. }
  66848. };
  66849. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  66850. var _this = this;
  66851. var updateVersion = function () {
  66852. // the version is not yet in the DB or we need to update it
  66853. _this._saveVersionIntoDBAsync(url, versionLoaded);
  66854. };
  66855. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  66856. };
  66857. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  66858. var _this = this;
  66859. if (this.isSupported && this.db) {
  66860. var version;
  66861. try {
  66862. var transaction = this.db.transaction(["versions"]);
  66863. transaction.oncomplete = function (event) {
  66864. if (version) {
  66865. // If the version in the JSON file is > than the version in DB
  66866. if (_this.manifestVersionFound > version.data) {
  66867. _this.mustUpdateRessources = true;
  66868. updateInDBCallback();
  66869. }
  66870. else {
  66871. callback(version.data);
  66872. }
  66873. }
  66874. else {
  66875. _this.mustUpdateRessources = true;
  66876. updateInDBCallback();
  66877. }
  66878. };
  66879. transaction.onabort = function (event) {
  66880. callback(-1);
  66881. };
  66882. var getRequest = transaction.objectStore("versions").get(url);
  66883. getRequest.onsuccess = function (event) {
  66884. version = (event.target).result;
  66885. };
  66886. getRequest.onerror = function (event) {
  66887. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  66888. callback(-1);
  66889. };
  66890. }
  66891. catch (ex) {
  66892. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  66893. callback(-1);
  66894. }
  66895. }
  66896. else {
  66897. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  66898. callback(-1);
  66899. }
  66900. };
  66901. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  66902. var _this = this;
  66903. if (this.isSupported && !this.hasReachedQuota && this.db) {
  66904. try {
  66905. // Open a transaction to the database
  66906. var transaction = this.db.transaction(["versions"], "readwrite");
  66907. // the transaction could abort because of a QuotaExceededError error
  66908. transaction.onabort = function (event) {
  66909. try {
  66910. var error = event.srcElement['error'];
  66911. if (error && error.name === "QuotaExceededError") {
  66912. _this.hasReachedQuota = true;
  66913. }
  66914. }
  66915. catch (ex) { }
  66916. callback(-1);
  66917. };
  66918. transaction.oncomplete = function (event) {
  66919. callback(_this.manifestVersionFound);
  66920. };
  66921. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  66922. // Put the scene into the database
  66923. var addRequest = transaction.objectStore("versions").put(newVersion);
  66924. addRequest.onsuccess = function (event) {
  66925. };
  66926. addRequest.onerror = function (event) {
  66927. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  66928. };
  66929. }
  66930. catch (ex) {
  66931. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  66932. callback(-1);
  66933. }
  66934. }
  66935. else {
  66936. callback(-1);
  66937. }
  66938. };
  66939. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  66940. var _this = this;
  66941. var completeUrl = Database.ReturnFullUrlLocation(url);
  66942. var saveAndLoadFile = function () {
  66943. // the scene is not yet in the DB, let's try to save it
  66944. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  66945. };
  66946. this._checkVersionFromDB(completeUrl, function (version) {
  66947. if (version !== -1) {
  66948. if (!_this.mustUpdateRessources) {
  66949. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  66950. }
  66951. else {
  66952. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  66953. }
  66954. }
  66955. else {
  66956. if (errorCallback) {
  66957. errorCallback();
  66958. }
  66959. }
  66960. });
  66961. };
  66962. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  66963. if (this.isSupported && this.db) {
  66964. var targetStore;
  66965. if (url.indexOf(".babylon") !== -1) {
  66966. targetStore = "scenes";
  66967. }
  66968. else {
  66969. targetStore = "textures";
  66970. }
  66971. var file;
  66972. var transaction = this.db.transaction([targetStore]);
  66973. transaction.oncomplete = function (event) {
  66974. if (file) {
  66975. callback(file.data);
  66976. }
  66977. else {
  66978. notInDBCallback();
  66979. }
  66980. };
  66981. transaction.onabort = function (event) {
  66982. notInDBCallback();
  66983. };
  66984. var getRequest = transaction.objectStore(targetStore).get(url);
  66985. getRequest.onsuccess = function (event) {
  66986. file = (event.target).result;
  66987. };
  66988. getRequest.onerror = function (event) {
  66989. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  66990. notInDBCallback();
  66991. };
  66992. }
  66993. else {
  66994. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  66995. callback();
  66996. }
  66997. };
  66998. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  66999. var _this = this;
  67000. if (this.isSupported) {
  67001. var targetStore;
  67002. if (url.indexOf(".babylon") !== -1) {
  67003. targetStore = "scenes";
  67004. }
  67005. else {
  67006. targetStore = "textures";
  67007. }
  67008. // Create XHR
  67009. var xhr = new XMLHttpRequest();
  67010. var fileData;
  67011. xhr.open("GET", url, true);
  67012. if (useArrayBuffer) {
  67013. xhr.responseType = "arraybuffer";
  67014. }
  67015. if (progressCallback) {
  67016. xhr.onprogress = progressCallback;
  67017. }
  67018. xhr.addEventListener("load", function () {
  67019. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  67020. // Blob as response (XHR2)
  67021. //fileData = xhr.responseText;
  67022. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  67023. if (!_this.hasReachedQuota && _this.db) {
  67024. // Open a transaction to the database
  67025. var transaction = _this.db.transaction([targetStore], "readwrite");
  67026. // the transaction could abort because of a QuotaExceededError error
  67027. transaction.onabort = function (event) {
  67028. try {
  67029. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  67030. var error = event.srcElement['error'];
  67031. if (error && error.name === "QuotaExceededError") {
  67032. _this.hasReachedQuota = true;
  67033. }
  67034. }
  67035. catch (ex) { }
  67036. callback(fileData);
  67037. };
  67038. transaction.oncomplete = function (event) {
  67039. callback(fileData);
  67040. };
  67041. var newFile;
  67042. if (targetStore === "scenes") {
  67043. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  67044. }
  67045. else {
  67046. newFile = { textureUrl: url, data: fileData };
  67047. }
  67048. try {
  67049. // Put the scene into the database
  67050. var addRequest = transaction.objectStore(targetStore).put(newFile);
  67051. addRequest.onsuccess = function (event) {
  67052. };
  67053. addRequest.onerror = function (event) {
  67054. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  67055. };
  67056. }
  67057. catch (ex) {
  67058. callback(fileData);
  67059. }
  67060. }
  67061. else {
  67062. callback(fileData);
  67063. }
  67064. }
  67065. else {
  67066. callback();
  67067. }
  67068. }, false);
  67069. xhr.addEventListener("error", function (event) {
  67070. BABYLON.Tools.Error("error on XHR request.");
  67071. callback();
  67072. }, false);
  67073. xhr.send();
  67074. }
  67075. else {
  67076. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  67077. callback();
  67078. }
  67079. };
  67080. Database.IsUASupportingBlobStorage = true;
  67081. Database.IDBStorageEnabled = true;
  67082. Database.parseURL = function (url) {
  67083. var a = document.createElement('a');
  67084. a.href = url;
  67085. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  67086. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  67087. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  67088. return absLocation;
  67089. };
  67090. Database.ReturnFullUrlLocation = function (url) {
  67091. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  67092. return (Database.parseURL(window.location.href) + url);
  67093. }
  67094. else {
  67095. return url;
  67096. }
  67097. };
  67098. return Database;
  67099. }());
  67100. BABYLON.Database = Database;
  67101. })(BABYLON || (BABYLON = {}));
  67102. //# sourceMappingURL=babylon.database.js.map
  67103. "use strict";
  67104. var BABYLON;
  67105. (function (BABYLON) {
  67106. var FresnelParameters = /** @class */ (function () {
  67107. function FresnelParameters() {
  67108. this._isEnabled = true;
  67109. this.leftColor = BABYLON.Color3.White();
  67110. this.rightColor = BABYLON.Color3.Black();
  67111. this.bias = 0;
  67112. this.power = 1;
  67113. }
  67114. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  67115. get: function () {
  67116. return this._isEnabled;
  67117. },
  67118. set: function (value) {
  67119. if (this._isEnabled === value) {
  67120. return;
  67121. }
  67122. this._isEnabled = value;
  67123. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  67124. },
  67125. enumerable: true,
  67126. configurable: true
  67127. });
  67128. FresnelParameters.prototype.clone = function () {
  67129. var newFresnelParameters = new FresnelParameters();
  67130. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  67131. return newFresnelParameters;
  67132. };
  67133. FresnelParameters.prototype.serialize = function () {
  67134. var serializationObject = {};
  67135. serializationObject.isEnabled = this.isEnabled;
  67136. serializationObject.leftColor = this.leftColor.asArray();
  67137. serializationObject.rightColor = this.rightColor.asArray();
  67138. serializationObject.bias = this.bias;
  67139. serializationObject.power = this.power;
  67140. return serializationObject;
  67141. };
  67142. FresnelParameters.Parse = function (parsedFresnelParameters) {
  67143. var fresnelParameters = new FresnelParameters();
  67144. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  67145. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  67146. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  67147. fresnelParameters.bias = parsedFresnelParameters.bias;
  67148. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  67149. return fresnelParameters;
  67150. };
  67151. return FresnelParameters;
  67152. }());
  67153. BABYLON.FresnelParameters = FresnelParameters;
  67154. })(BABYLON || (BABYLON = {}));
  67155. //# sourceMappingURL=babylon.fresnelParameters.js.map
  67156. "use strict";
  67157. var BABYLON;
  67158. (function (BABYLON) {
  67159. var MultiMaterial = /** @class */ (function (_super) {
  67160. __extends(MultiMaterial, _super);
  67161. function MultiMaterial(name, scene) {
  67162. var _this = _super.call(this, name, scene, true) || this;
  67163. scene.multiMaterials.push(_this);
  67164. _this.subMaterials = new Array();
  67165. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  67166. return _this;
  67167. }
  67168. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  67169. get: function () {
  67170. return this._subMaterials;
  67171. },
  67172. set: function (value) {
  67173. this._subMaterials = value;
  67174. this._hookArray(value);
  67175. },
  67176. enumerable: true,
  67177. configurable: true
  67178. });
  67179. MultiMaterial.prototype._hookArray = function (array) {
  67180. var _this = this;
  67181. var oldPush = array.push;
  67182. array.push = function () {
  67183. var items = [];
  67184. for (var _i = 0; _i < arguments.length; _i++) {
  67185. items[_i] = arguments[_i];
  67186. }
  67187. var result = oldPush.apply(array, items);
  67188. _this._markAllSubMeshesAsTexturesDirty();
  67189. return result;
  67190. };
  67191. var oldSplice = array.splice;
  67192. array.splice = function (index, deleteCount) {
  67193. var deleted = oldSplice.apply(array, [index, deleteCount]);
  67194. _this._markAllSubMeshesAsTexturesDirty();
  67195. return deleted;
  67196. };
  67197. };
  67198. // Properties
  67199. MultiMaterial.prototype.getSubMaterial = function (index) {
  67200. if (index < 0 || index >= this.subMaterials.length) {
  67201. return this.getScene().defaultMaterial;
  67202. }
  67203. return this.subMaterials[index];
  67204. };
  67205. MultiMaterial.prototype.getActiveTextures = function () {
  67206. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  67207. if (subMaterial) {
  67208. return subMaterial.getActiveTextures();
  67209. }
  67210. else {
  67211. return [];
  67212. }
  67213. }));
  67214. var _a;
  67215. };
  67216. // Methods
  67217. MultiMaterial.prototype.getClassName = function () {
  67218. return "MultiMaterial";
  67219. };
  67220. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  67221. for (var index = 0; index < this.subMaterials.length; index++) {
  67222. var subMaterial = this.subMaterials[index];
  67223. if (subMaterial) {
  67224. if (subMaterial.storeEffectOnSubMeshes) {
  67225. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  67226. return false;
  67227. }
  67228. continue;
  67229. }
  67230. if (!subMaterial.isReady(mesh)) {
  67231. return false;
  67232. }
  67233. }
  67234. }
  67235. return true;
  67236. };
  67237. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  67238. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  67239. for (var index = 0; index < this.subMaterials.length; index++) {
  67240. var subMaterial = null;
  67241. var current = this.subMaterials[index];
  67242. if (cloneChildren && current) {
  67243. subMaterial = current.clone(name + "-" + current.name);
  67244. }
  67245. else {
  67246. subMaterial = this.subMaterials[index];
  67247. }
  67248. newMultiMaterial.subMaterials.push(subMaterial);
  67249. }
  67250. return newMultiMaterial;
  67251. };
  67252. MultiMaterial.prototype.serialize = function () {
  67253. var serializationObject = {};
  67254. serializationObject.name = this.name;
  67255. serializationObject.id = this.id;
  67256. if (BABYLON.Tags) {
  67257. serializationObject.tags = BABYLON.Tags.GetTags(this);
  67258. }
  67259. serializationObject.materials = [];
  67260. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  67261. var subMat = this.subMaterials[matIndex];
  67262. if (subMat) {
  67263. serializationObject.materials.push(subMat.id);
  67264. }
  67265. else {
  67266. serializationObject.materials.push(null);
  67267. }
  67268. }
  67269. return serializationObject;
  67270. };
  67271. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  67272. var scene = this.getScene();
  67273. if (!scene) {
  67274. return;
  67275. }
  67276. var index = scene.multiMaterials.indexOf(this);
  67277. if (index >= 0) {
  67278. scene.multiMaterials.splice(index, 1);
  67279. }
  67280. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  67281. };
  67282. return MultiMaterial;
  67283. }(BABYLON.Material));
  67284. BABYLON.MultiMaterial = MultiMaterial;
  67285. })(BABYLON || (BABYLON = {}));
  67286. //# sourceMappingURL=babylon.multiMaterial.js.map
  67287. "use strict";
  67288. var BABYLON;
  67289. (function (BABYLON) {
  67290. var FreeCameraTouchInput = /** @class */ (function () {
  67291. function FreeCameraTouchInput() {
  67292. this._offsetX = null;
  67293. this._offsetY = null;
  67294. this._pointerPressed = new Array();
  67295. this.touchAngularSensibility = 200000.0;
  67296. this.touchMoveSensibility = 250.0;
  67297. }
  67298. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  67299. var _this = this;
  67300. var previousPosition = null;
  67301. if (this._pointerInput === undefined) {
  67302. this._onLostFocus = function (evt) {
  67303. _this._offsetX = null;
  67304. _this._offsetY = null;
  67305. };
  67306. this._pointerInput = function (p, s) {
  67307. var evt = p.event;
  67308. if (evt.pointerType === "mouse") {
  67309. return;
  67310. }
  67311. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  67312. if (!noPreventDefault) {
  67313. evt.preventDefault();
  67314. }
  67315. _this._pointerPressed.push(evt.pointerId);
  67316. if (_this._pointerPressed.length !== 1) {
  67317. return;
  67318. }
  67319. previousPosition = {
  67320. x: evt.clientX,
  67321. y: evt.clientY
  67322. };
  67323. }
  67324. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  67325. if (!noPreventDefault) {
  67326. evt.preventDefault();
  67327. }
  67328. var index = _this._pointerPressed.indexOf(evt.pointerId);
  67329. if (index === -1) {
  67330. return;
  67331. }
  67332. _this._pointerPressed.splice(index, 1);
  67333. if (index != 0) {
  67334. return;
  67335. }
  67336. previousPosition = null;
  67337. _this._offsetX = null;
  67338. _this._offsetY = null;
  67339. }
  67340. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  67341. if (!noPreventDefault) {
  67342. evt.preventDefault();
  67343. }
  67344. if (!previousPosition) {
  67345. return;
  67346. }
  67347. var index = _this._pointerPressed.indexOf(evt.pointerId);
  67348. if (index != 0) {
  67349. return;
  67350. }
  67351. _this._offsetX = evt.clientX - previousPosition.x;
  67352. _this._offsetY = -(evt.clientY - previousPosition.y);
  67353. }
  67354. };
  67355. }
  67356. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  67357. if (this._onLostFocus) {
  67358. element.addEventListener("blur", this._onLostFocus);
  67359. }
  67360. };
  67361. FreeCameraTouchInput.prototype.detachControl = function (element) {
  67362. if (this._pointerInput && element) {
  67363. if (this._observer) {
  67364. this.camera.getScene().onPointerObservable.remove(this._observer);
  67365. this._observer = null;
  67366. }
  67367. if (this._onLostFocus) {
  67368. element.removeEventListener("blur", this._onLostFocus);
  67369. this._onLostFocus = null;
  67370. }
  67371. this._pointerPressed = [];
  67372. this._offsetX = null;
  67373. this._offsetY = null;
  67374. }
  67375. };
  67376. FreeCameraTouchInput.prototype.checkInputs = function () {
  67377. if (this._offsetX && this._offsetY) {
  67378. var camera = this.camera;
  67379. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  67380. if (this._pointerPressed.length > 1) {
  67381. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  67382. }
  67383. else {
  67384. var speed = camera._computeLocalCameraSpeed();
  67385. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  67386. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  67387. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  67388. }
  67389. }
  67390. };
  67391. FreeCameraTouchInput.prototype.getClassName = function () {
  67392. return "FreeCameraTouchInput";
  67393. };
  67394. FreeCameraTouchInput.prototype.getSimpleName = function () {
  67395. return "touch";
  67396. };
  67397. __decorate([
  67398. BABYLON.serialize()
  67399. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  67400. __decorate([
  67401. BABYLON.serialize()
  67402. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  67403. return FreeCameraTouchInput;
  67404. }());
  67405. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  67406. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  67407. })(BABYLON || (BABYLON = {}));
  67408. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  67409. "use strict";
  67410. var BABYLON;
  67411. (function (BABYLON) {
  67412. // We're mainly based on the logic defined into the FreeCamera code
  67413. var TouchCamera = /** @class */ (function (_super) {
  67414. __extends(TouchCamera, _super);
  67415. //-- end properties for backward compatibility for inputs
  67416. function TouchCamera(name, position, scene) {
  67417. var _this = _super.call(this, name, position, scene) || this;
  67418. _this.inputs.addTouch();
  67419. _this._setupInputs();
  67420. return _this;
  67421. }
  67422. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  67423. //-- Begin properties for backward compatibility for inputs
  67424. get: function () {
  67425. var touch = this.inputs.attached["touch"];
  67426. if (touch)
  67427. return touch.touchAngularSensibility;
  67428. return 0;
  67429. },
  67430. set: function (value) {
  67431. var touch = this.inputs.attached["touch"];
  67432. if (touch)
  67433. touch.touchAngularSensibility = value;
  67434. },
  67435. enumerable: true,
  67436. configurable: true
  67437. });
  67438. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  67439. get: function () {
  67440. var touch = this.inputs.attached["touch"];
  67441. if (touch)
  67442. return touch.touchMoveSensibility;
  67443. return 0;
  67444. },
  67445. set: function (value) {
  67446. var touch = this.inputs.attached["touch"];
  67447. if (touch)
  67448. touch.touchMoveSensibility = value;
  67449. },
  67450. enumerable: true,
  67451. configurable: true
  67452. });
  67453. TouchCamera.prototype.getClassName = function () {
  67454. return "TouchCamera";
  67455. };
  67456. TouchCamera.prototype._setupInputs = function () {
  67457. var mouse = this.inputs.attached["mouse"];
  67458. if (mouse) {
  67459. mouse.touchEnabled = false;
  67460. }
  67461. };
  67462. return TouchCamera;
  67463. }(BABYLON.FreeCamera));
  67464. BABYLON.TouchCamera = TouchCamera;
  67465. })(BABYLON || (BABYLON = {}));
  67466. //# sourceMappingURL=babylon.touchCamera.js.map
  67467. "use strict";
  67468. var BABYLON;
  67469. (function (BABYLON) {
  67470. var ProceduralTexture = /** @class */ (function (_super) {
  67471. __extends(ProceduralTexture, _super);
  67472. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  67473. if (fallbackTexture === void 0) { fallbackTexture = null; }
  67474. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67475. if (isCube === void 0) { isCube = false; }
  67476. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  67477. _this.isCube = isCube;
  67478. _this.isEnabled = true;
  67479. _this._currentRefreshId = -1;
  67480. _this._refreshRate = 1;
  67481. _this._vertexBuffers = {};
  67482. _this._uniforms = new Array();
  67483. _this._samplers = new Array();
  67484. _this._textures = {};
  67485. _this._floats = {};
  67486. _this._floatsArrays = {};
  67487. _this._colors3 = {};
  67488. _this._colors4 = {};
  67489. _this._vectors2 = {};
  67490. _this._vectors3 = {};
  67491. _this._matrices = {};
  67492. _this._fallbackTextureUsed = false;
  67493. scene.proceduralTextures.push(_this);
  67494. _this._engine = scene.getEngine();
  67495. _this.name = name;
  67496. _this.isRenderTarget = true;
  67497. _this._size = size;
  67498. _this._generateMipMaps = generateMipMaps;
  67499. _this.setFragment(fragment);
  67500. _this._fallbackTexture = fallbackTexture;
  67501. if (isCube) {
  67502. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  67503. _this.setFloat("face", 0);
  67504. }
  67505. else {
  67506. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  67507. }
  67508. // VBO
  67509. var vertices = [];
  67510. vertices.push(1, 1);
  67511. vertices.push(-1, 1);
  67512. vertices.push(-1, -1);
  67513. vertices.push(1, -1);
  67514. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  67515. _this._createIndexBuffer();
  67516. return _this;
  67517. }
  67518. ProceduralTexture.prototype._createIndexBuffer = function () {
  67519. var engine = this._engine;
  67520. // Indices
  67521. var indices = [];
  67522. indices.push(0);
  67523. indices.push(1);
  67524. indices.push(2);
  67525. indices.push(0);
  67526. indices.push(2);
  67527. indices.push(3);
  67528. this._indexBuffer = engine.createIndexBuffer(indices);
  67529. };
  67530. ProceduralTexture.prototype._rebuild = function () {
  67531. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  67532. if (vb) {
  67533. vb._rebuild();
  67534. }
  67535. this._createIndexBuffer();
  67536. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  67537. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  67538. }
  67539. };
  67540. ProceduralTexture.prototype.reset = function () {
  67541. if (this._effect === undefined) {
  67542. return;
  67543. }
  67544. var engine = this._engine;
  67545. engine._releaseEffect(this._effect);
  67546. };
  67547. ProceduralTexture.prototype.isReady = function () {
  67548. var _this = this;
  67549. var engine = this._engine;
  67550. var shaders;
  67551. if (!this._fragment) {
  67552. return false;
  67553. }
  67554. if (this._fallbackTextureUsed) {
  67555. return true;
  67556. }
  67557. if (this._fragment.fragmentElement !== undefined) {
  67558. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  67559. }
  67560. else {
  67561. shaders = { vertex: "procedural", fragment: this._fragment };
  67562. }
  67563. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  67564. _this.releaseInternalTexture();
  67565. if (_this._fallbackTexture) {
  67566. _this._texture = _this._fallbackTexture._texture;
  67567. if (_this._texture) {
  67568. _this._texture.incrementReferences();
  67569. }
  67570. }
  67571. _this._fallbackTextureUsed = true;
  67572. });
  67573. return this._effect.isReady();
  67574. };
  67575. ProceduralTexture.prototype.resetRefreshCounter = function () {
  67576. this._currentRefreshId = -1;
  67577. };
  67578. ProceduralTexture.prototype.setFragment = function (fragment) {
  67579. this._fragment = fragment;
  67580. };
  67581. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  67582. get: function () {
  67583. return this._refreshRate;
  67584. },
  67585. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  67586. set: function (value) {
  67587. this._refreshRate = value;
  67588. this.resetRefreshCounter();
  67589. },
  67590. enumerable: true,
  67591. configurable: true
  67592. });
  67593. ProceduralTexture.prototype._shouldRender = function () {
  67594. if (!this.isEnabled || !this.isReady() || !this._texture) {
  67595. return false;
  67596. }
  67597. if (this._fallbackTextureUsed) {
  67598. return false;
  67599. }
  67600. if (this._currentRefreshId === -1) {
  67601. this._currentRefreshId = 1;
  67602. return true;
  67603. }
  67604. if (this.refreshRate === this._currentRefreshId) {
  67605. this._currentRefreshId = 1;
  67606. return true;
  67607. }
  67608. this._currentRefreshId++;
  67609. return false;
  67610. };
  67611. ProceduralTexture.prototype.getRenderSize = function () {
  67612. return this._size;
  67613. };
  67614. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  67615. if (this._fallbackTextureUsed) {
  67616. return;
  67617. }
  67618. this.releaseInternalTexture();
  67619. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  67620. };
  67621. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  67622. if (this._uniforms.indexOf(uniformName) === -1) {
  67623. this._uniforms.push(uniformName);
  67624. }
  67625. };
  67626. ProceduralTexture.prototype.setTexture = function (name, texture) {
  67627. if (this._samplers.indexOf(name) === -1) {
  67628. this._samplers.push(name);
  67629. }
  67630. this._textures[name] = texture;
  67631. return this;
  67632. };
  67633. ProceduralTexture.prototype.setFloat = function (name, value) {
  67634. this._checkUniform(name);
  67635. this._floats[name] = value;
  67636. return this;
  67637. };
  67638. ProceduralTexture.prototype.setFloats = function (name, value) {
  67639. this._checkUniform(name);
  67640. this._floatsArrays[name] = value;
  67641. return this;
  67642. };
  67643. ProceduralTexture.prototype.setColor3 = function (name, value) {
  67644. this._checkUniform(name);
  67645. this._colors3[name] = value;
  67646. return this;
  67647. };
  67648. ProceduralTexture.prototype.setColor4 = function (name, value) {
  67649. this._checkUniform(name);
  67650. this._colors4[name] = value;
  67651. return this;
  67652. };
  67653. ProceduralTexture.prototype.setVector2 = function (name, value) {
  67654. this._checkUniform(name);
  67655. this._vectors2[name] = value;
  67656. return this;
  67657. };
  67658. ProceduralTexture.prototype.setVector3 = function (name, value) {
  67659. this._checkUniform(name);
  67660. this._vectors3[name] = value;
  67661. return this;
  67662. };
  67663. ProceduralTexture.prototype.setMatrix = function (name, value) {
  67664. this._checkUniform(name);
  67665. this._matrices[name] = value;
  67666. return this;
  67667. };
  67668. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  67669. var scene = this.getScene();
  67670. if (!scene) {
  67671. return;
  67672. }
  67673. var engine = this._engine;
  67674. // Render
  67675. engine.enableEffect(this._effect);
  67676. engine.setState(false);
  67677. // Texture
  67678. for (var name in this._textures) {
  67679. this._effect.setTexture(name, this._textures[name]);
  67680. }
  67681. // Float
  67682. for (name in this._floats) {
  67683. this._effect.setFloat(name, this._floats[name]);
  67684. }
  67685. // Floats
  67686. for (name in this._floatsArrays) {
  67687. this._effect.setArray(name, this._floatsArrays[name]);
  67688. }
  67689. // Color3
  67690. for (name in this._colors3) {
  67691. this._effect.setColor3(name, this._colors3[name]);
  67692. }
  67693. // Color4
  67694. for (name in this._colors4) {
  67695. var color = this._colors4[name];
  67696. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  67697. }
  67698. // Vector2
  67699. for (name in this._vectors2) {
  67700. this._effect.setVector2(name, this._vectors2[name]);
  67701. }
  67702. // Vector3
  67703. for (name in this._vectors3) {
  67704. this._effect.setVector3(name, this._vectors3[name]);
  67705. }
  67706. // Matrix
  67707. for (name in this._matrices) {
  67708. this._effect.setMatrix(name, this._matrices[name]);
  67709. }
  67710. if (!this._texture) {
  67711. return;
  67712. }
  67713. if (this.isCube) {
  67714. for (var face = 0; face < 6; face++) {
  67715. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  67716. // VBOs
  67717. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  67718. this._effect.setFloat("face", face);
  67719. // Clear
  67720. engine.clear(scene.clearColor, true, true, true);
  67721. // Draw order
  67722. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  67723. // Mipmaps
  67724. if (face === 5) {
  67725. engine.generateMipMapsForCubemap(this._texture);
  67726. }
  67727. }
  67728. }
  67729. else {
  67730. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  67731. // VBOs
  67732. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  67733. // Clear
  67734. engine.clear(scene.clearColor, true, true, true);
  67735. // Draw order
  67736. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  67737. }
  67738. // Unbind
  67739. engine.unBindFramebuffer(this._texture, this.isCube);
  67740. if (this.onGenerated) {
  67741. this.onGenerated();
  67742. }
  67743. };
  67744. ProceduralTexture.prototype.clone = function () {
  67745. var textureSize = this.getSize();
  67746. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  67747. // Base texture
  67748. newTexture.hasAlpha = this.hasAlpha;
  67749. newTexture.level = this.level;
  67750. // RenderTarget Texture
  67751. newTexture.coordinatesMode = this.coordinatesMode;
  67752. return newTexture;
  67753. };
  67754. ProceduralTexture.prototype.dispose = function () {
  67755. var scene = this.getScene();
  67756. if (!scene) {
  67757. return;
  67758. }
  67759. var index = scene.proceduralTextures.indexOf(this);
  67760. if (index >= 0) {
  67761. scene.proceduralTextures.splice(index, 1);
  67762. }
  67763. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  67764. if (vertexBuffer) {
  67765. vertexBuffer.dispose();
  67766. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  67767. }
  67768. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  67769. this._indexBuffer = null;
  67770. }
  67771. _super.prototype.dispose.call(this);
  67772. };
  67773. return ProceduralTexture;
  67774. }(BABYLON.Texture));
  67775. BABYLON.ProceduralTexture = ProceduralTexture;
  67776. })(BABYLON || (BABYLON = {}));
  67777. //# sourceMappingURL=babylon.proceduralTexture.js.map
  67778. "use strict";
  67779. var BABYLON;
  67780. (function (BABYLON) {
  67781. var CustomProceduralTexture = /** @class */ (function (_super) {
  67782. __extends(CustomProceduralTexture, _super);
  67783. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  67784. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  67785. _this._animate = true;
  67786. _this._time = 0;
  67787. _this._texturePath = texturePath;
  67788. //Try to load json
  67789. _this.loadJson(texturePath);
  67790. _this.refreshRate = 1;
  67791. return _this;
  67792. }
  67793. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  67794. var _this = this;
  67795. var noConfigFile = function () {
  67796. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  67797. try {
  67798. _this.setFragment(_this._texturePath);
  67799. }
  67800. catch (ex) {
  67801. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  67802. }
  67803. };
  67804. var configFileUrl = jsonUrl + "/config.json";
  67805. var xhr = new XMLHttpRequest();
  67806. xhr.open("GET", configFileUrl, true);
  67807. xhr.addEventListener("load", function () {
  67808. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  67809. try {
  67810. _this._config = JSON.parse(xhr.response);
  67811. _this.updateShaderUniforms();
  67812. _this.updateTextures();
  67813. _this.setFragment(_this._texturePath + "/custom");
  67814. _this._animate = _this._config.animate;
  67815. _this.refreshRate = _this._config.refreshrate;
  67816. }
  67817. catch (ex) {
  67818. noConfigFile();
  67819. }
  67820. }
  67821. else {
  67822. noConfigFile();
  67823. }
  67824. }, false);
  67825. xhr.addEventListener("error", function () {
  67826. noConfigFile();
  67827. }, false);
  67828. try {
  67829. xhr.send();
  67830. }
  67831. catch (ex) {
  67832. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  67833. }
  67834. };
  67835. CustomProceduralTexture.prototype.isReady = function () {
  67836. if (!_super.prototype.isReady.call(this)) {
  67837. return false;
  67838. }
  67839. for (var name in this._textures) {
  67840. var texture = this._textures[name];
  67841. if (!texture.isReady()) {
  67842. return false;
  67843. }
  67844. }
  67845. return true;
  67846. };
  67847. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  67848. var scene = this.getScene();
  67849. if (this._animate && scene) {
  67850. this._time += scene.getAnimationRatio() * 0.03;
  67851. this.updateShaderUniforms();
  67852. }
  67853. _super.prototype.render.call(this, useCameraPostProcess);
  67854. };
  67855. CustomProceduralTexture.prototype.updateTextures = function () {
  67856. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  67857. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  67858. }
  67859. };
  67860. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  67861. if (this._config) {
  67862. for (var j = 0; j < this._config.uniforms.length; j++) {
  67863. var uniform = this._config.uniforms[j];
  67864. switch (uniform.type) {
  67865. case "float":
  67866. this.setFloat(uniform.name, uniform.value);
  67867. break;
  67868. case "color3":
  67869. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  67870. break;
  67871. case "color4":
  67872. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  67873. break;
  67874. case "vector2":
  67875. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  67876. break;
  67877. case "vector3":
  67878. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  67879. break;
  67880. }
  67881. }
  67882. }
  67883. this.setFloat("time", this._time);
  67884. };
  67885. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  67886. get: function () {
  67887. return this._animate;
  67888. },
  67889. set: function (value) {
  67890. this._animate = value;
  67891. },
  67892. enumerable: true,
  67893. configurable: true
  67894. });
  67895. return CustomProceduralTexture;
  67896. }(BABYLON.ProceduralTexture));
  67897. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  67898. })(BABYLON || (BABYLON = {}));
  67899. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  67900. "use strict";
  67901. var BABYLON;
  67902. (function (BABYLON) {
  67903. var FreeCameraGamepadInput = /** @class */ (function () {
  67904. function FreeCameraGamepadInput() {
  67905. this.gamepadAngularSensibility = 200;
  67906. this.gamepadMoveSensibility = 40;
  67907. // private members
  67908. this._cameraTransform = BABYLON.Matrix.Identity();
  67909. this._deltaTransform = BABYLON.Vector3.Zero();
  67910. this._vector3 = BABYLON.Vector3.Zero();
  67911. this._vector2 = BABYLON.Vector2.Zero();
  67912. }
  67913. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  67914. var _this = this;
  67915. var manager = this.camera.getScene().gamepadManager;
  67916. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  67917. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  67918. // prioritize XBOX gamepads.
  67919. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  67920. _this.gamepad = gamepad;
  67921. }
  67922. }
  67923. });
  67924. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  67925. if (_this.gamepad === gamepad) {
  67926. _this.gamepad = null;
  67927. }
  67928. });
  67929. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  67930. };
  67931. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  67932. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  67933. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  67934. this.gamepad = null;
  67935. };
  67936. FreeCameraGamepadInput.prototype.checkInputs = function () {
  67937. if (this.gamepad && this.gamepad.leftStick) {
  67938. var camera = this.camera;
  67939. var LSValues = this.gamepad.leftStick;
  67940. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  67941. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  67942. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  67943. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  67944. var RSValues = this.gamepad.rightStick;
  67945. if (RSValues) {
  67946. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  67947. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  67948. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  67949. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  67950. }
  67951. else {
  67952. RSValues = { x: 0, y: 0 };
  67953. }
  67954. if (!camera.rotationQuaternion) {
  67955. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  67956. }
  67957. else {
  67958. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  67959. }
  67960. var speed = camera._computeLocalCameraSpeed() * 50.0;
  67961. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  67962. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  67963. camera.cameraDirection.addInPlace(this._deltaTransform);
  67964. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  67965. camera.cameraRotation.addInPlace(this._vector2);
  67966. }
  67967. };
  67968. FreeCameraGamepadInput.prototype.getClassName = function () {
  67969. return "FreeCameraGamepadInput";
  67970. };
  67971. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  67972. return "gamepad";
  67973. };
  67974. __decorate([
  67975. BABYLON.serialize()
  67976. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  67977. __decorate([
  67978. BABYLON.serialize()
  67979. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  67980. return FreeCameraGamepadInput;
  67981. }());
  67982. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  67983. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  67984. })(BABYLON || (BABYLON = {}));
  67985. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  67986. "use strict";
  67987. var BABYLON;
  67988. (function (BABYLON) {
  67989. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  67990. function ArcRotateCameraGamepadInput() {
  67991. this.gamepadRotationSensibility = 80;
  67992. this.gamepadMoveSensibility = 40;
  67993. }
  67994. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  67995. var _this = this;
  67996. var manager = this.camera.getScene().gamepadManager;
  67997. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  67998. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  67999. // prioritize XBOX gamepads.
  68000. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  68001. _this.gamepad = gamepad;
  68002. }
  68003. }
  68004. });
  68005. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  68006. if (_this.gamepad === gamepad) {
  68007. _this.gamepad = null;
  68008. }
  68009. });
  68010. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  68011. };
  68012. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  68013. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  68014. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  68015. this.gamepad = null;
  68016. };
  68017. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  68018. if (this.gamepad) {
  68019. var camera = this.camera;
  68020. var RSValues = this.gamepad.rightStick;
  68021. if (RSValues) {
  68022. if (RSValues.x != 0) {
  68023. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  68024. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  68025. camera.inertialAlphaOffset += normalizedRX;
  68026. }
  68027. }
  68028. if (RSValues.y != 0) {
  68029. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  68030. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  68031. camera.inertialBetaOffset += normalizedRY;
  68032. }
  68033. }
  68034. }
  68035. var LSValues = this.gamepad.leftStick;
  68036. if (LSValues && LSValues.y != 0) {
  68037. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  68038. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  68039. this.camera.inertialRadiusOffset -= normalizedLY;
  68040. }
  68041. }
  68042. }
  68043. };
  68044. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  68045. return "ArcRotateCameraGamepadInput";
  68046. };
  68047. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  68048. return "gamepad";
  68049. };
  68050. __decorate([
  68051. BABYLON.serialize()
  68052. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  68053. __decorate([
  68054. BABYLON.serialize()
  68055. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  68056. return ArcRotateCameraGamepadInput;
  68057. }());
  68058. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  68059. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  68060. })(BABYLON || (BABYLON = {}));
  68061. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  68062. "use strict";
  68063. var BABYLON;
  68064. (function (BABYLON) {
  68065. var GamepadManager = /** @class */ (function () {
  68066. function GamepadManager(_scene) {
  68067. var _this = this;
  68068. this._scene = _scene;
  68069. this._babylonGamepads = [];
  68070. this._oneGamepadConnected = false;
  68071. this._isMonitoring = false;
  68072. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  68073. if (!BABYLON.Tools.IsWindowObjectExist()) {
  68074. this._gamepadEventSupported = false;
  68075. }
  68076. else {
  68077. this._gamepadEventSupported = 'GamepadEvent' in window;
  68078. this._gamepadSupport = (navigator.getGamepads ||
  68079. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  68080. }
  68081. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  68082. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  68083. for (var i in _this._babylonGamepads) {
  68084. var gamepad = _this._babylonGamepads[i];
  68085. if (gamepad && gamepad._isConnected) {
  68086. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  68087. }
  68088. }
  68089. });
  68090. this._onGamepadConnectedEvent = function (evt) {
  68091. var gamepad = evt.gamepad;
  68092. if (gamepad.index in _this._babylonGamepads) {
  68093. if (_this._babylonGamepads[gamepad.index].isConnected) {
  68094. return;
  68095. }
  68096. }
  68097. var newGamepad;
  68098. if (_this._babylonGamepads[gamepad.index]) {
  68099. newGamepad = _this._babylonGamepads[gamepad.index];
  68100. newGamepad.browserGamepad = gamepad;
  68101. newGamepad._isConnected = true;
  68102. }
  68103. else {
  68104. newGamepad = _this._addNewGamepad(gamepad);
  68105. }
  68106. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  68107. _this._startMonitoringGamepads();
  68108. };
  68109. this._onGamepadDisconnectedEvent = function (evt) {
  68110. var gamepad = evt.gamepad;
  68111. // Remove the gamepad from the list of gamepads to monitor.
  68112. for (var i in _this._babylonGamepads) {
  68113. if (_this._babylonGamepads[i].index === gamepad.index) {
  68114. var disconnectedGamepad = _this._babylonGamepads[i];
  68115. disconnectedGamepad._isConnected = false;
  68116. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  68117. break;
  68118. }
  68119. }
  68120. };
  68121. if (this._gamepadSupport) {
  68122. //first add already-connected gamepads
  68123. this._updateGamepadObjects();
  68124. if (this._babylonGamepads.length) {
  68125. this._startMonitoringGamepads();
  68126. }
  68127. // Checking if the gamepad connected event is supported (like in Firefox)
  68128. if (this._gamepadEventSupported) {
  68129. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  68130. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  68131. }
  68132. else {
  68133. this._startMonitoringGamepads();
  68134. }
  68135. }
  68136. }
  68137. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  68138. get: function () {
  68139. return this._babylonGamepads;
  68140. },
  68141. enumerable: true,
  68142. configurable: true
  68143. });
  68144. GamepadManager.prototype.getGamepadByType = function (type) {
  68145. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  68146. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  68147. var gamepad = _a[_i];
  68148. if (gamepad && gamepad.type === type) {
  68149. return gamepad;
  68150. }
  68151. }
  68152. return null;
  68153. };
  68154. GamepadManager.prototype.dispose = function () {
  68155. if (this._gamepadEventSupported) {
  68156. if (this._onGamepadConnectedEvent) {
  68157. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  68158. }
  68159. if (this._onGamepadDisconnectedEvent) {
  68160. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  68161. }
  68162. this._onGamepadConnectedEvent = null;
  68163. this._onGamepadDisconnectedEvent = null;
  68164. }
  68165. this._babylonGamepads.forEach(function (gamepad) {
  68166. gamepad.dispose();
  68167. });
  68168. this.onGamepadConnectedObservable.clear();
  68169. this.onGamepadDisconnectedObservable.clear();
  68170. this._oneGamepadConnected = false;
  68171. this._stopMonitoringGamepads();
  68172. this._babylonGamepads = [];
  68173. };
  68174. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  68175. if (!this._oneGamepadConnected) {
  68176. this._oneGamepadConnected = true;
  68177. }
  68178. var newGamepad;
  68179. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  68180. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  68181. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  68182. }
  68183. else if (gamepad.pose) {
  68184. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  68185. }
  68186. else {
  68187. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  68188. }
  68189. this._babylonGamepads[newGamepad.index] = newGamepad;
  68190. return newGamepad;
  68191. };
  68192. GamepadManager.prototype._startMonitoringGamepads = function () {
  68193. if (!this._isMonitoring) {
  68194. this._isMonitoring = true;
  68195. //back-comp
  68196. if (!this._scene) {
  68197. this._checkGamepadsStatus();
  68198. }
  68199. }
  68200. };
  68201. GamepadManager.prototype._stopMonitoringGamepads = function () {
  68202. this._isMonitoring = false;
  68203. };
  68204. GamepadManager.prototype._checkGamepadsStatus = function () {
  68205. var _this = this;
  68206. // Hack to be compatible Chrome
  68207. this._updateGamepadObjects();
  68208. for (var i in this._babylonGamepads) {
  68209. var gamepad = this._babylonGamepads[i];
  68210. if (!gamepad || !gamepad.isConnected) {
  68211. continue;
  68212. }
  68213. gamepad.update();
  68214. }
  68215. if (this._isMonitoring && !this._scene) {
  68216. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  68217. }
  68218. };
  68219. // This function is called only on Chrome, which does not properly support
  68220. // connection/disconnection events and forces you to recopy again the gamepad object
  68221. GamepadManager.prototype._updateGamepadObjects = function () {
  68222. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  68223. for (var i = 0; i < gamepads.length; i++) {
  68224. if (gamepads[i]) {
  68225. if (!this._babylonGamepads[gamepads[i].index]) {
  68226. var newGamepad = this._addNewGamepad(gamepads[i]);
  68227. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  68228. }
  68229. else {
  68230. // Forced to copy again this object for Chrome for unknown reason
  68231. this._babylonGamepads[i].browserGamepad = gamepads[i];
  68232. if (!this._babylonGamepads[i].isConnected) {
  68233. this._babylonGamepads[i]._isConnected = true;
  68234. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  68235. }
  68236. }
  68237. }
  68238. }
  68239. };
  68240. return GamepadManager;
  68241. }());
  68242. BABYLON.GamepadManager = GamepadManager;
  68243. })(BABYLON || (BABYLON = {}));
  68244. //# sourceMappingURL=babylon.gamepadManager.js.map
  68245. "use strict";
  68246. var BABYLON;
  68247. (function (BABYLON) {
  68248. var StickValues = /** @class */ (function () {
  68249. function StickValues(x, y) {
  68250. this.x = x;
  68251. this.y = y;
  68252. }
  68253. return StickValues;
  68254. }());
  68255. BABYLON.StickValues = StickValues;
  68256. var Gamepad = /** @class */ (function () {
  68257. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  68258. if (leftStickX === void 0) { leftStickX = 0; }
  68259. if (leftStickY === void 0) { leftStickY = 1; }
  68260. if (rightStickX === void 0) { rightStickX = 2; }
  68261. if (rightStickY === void 0) { rightStickY = 3; }
  68262. this.id = id;
  68263. this.index = index;
  68264. this.browserGamepad = browserGamepad;
  68265. this._isConnected = true;
  68266. this._invertLeftStickY = false;
  68267. this.type = Gamepad.GAMEPAD;
  68268. this._leftStickAxisX = leftStickX;
  68269. this._leftStickAxisY = leftStickY;
  68270. this._rightStickAxisX = rightStickX;
  68271. this._rightStickAxisY = rightStickY;
  68272. if (this.browserGamepad.axes.length >= 2) {
  68273. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  68274. }
  68275. if (this.browserGamepad.axes.length >= 4) {
  68276. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  68277. }
  68278. }
  68279. Object.defineProperty(Gamepad.prototype, "isConnected", {
  68280. get: function () {
  68281. return this._isConnected;
  68282. },
  68283. enumerable: true,
  68284. configurable: true
  68285. });
  68286. Gamepad.prototype.onleftstickchanged = function (callback) {
  68287. this._onleftstickchanged = callback;
  68288. };
  68289. Gamepad.prototype.onrightstickchanged = function (callback) {
  68290. this._onrightstickchanged = callback;
  68291. };
  68292. Object.defineProperty(Gamepad.prototype, "leftStick", {
  68293. get: function () {
  68294. return this._leftStick;
  68295. },
  68296. set: function (newValues) {
  68297. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  68298. this._onleftstickchanged(newValues);
  68299. }
  68300. this._leftStick = newValues;
  68301. },
  68302. enumerable: true,
  68303. configurable: true
  68304. });
  68305. Object.defineProperty(Gamepad.prototype, "rightStick", {
  68306. get: function () {
  68307. return this._rightStick;
  68308. },
  68309. set: function (newValues) {
  68310. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  68311. this._onrightstickchanged(newValues);
  68312. }
  68313. this._rightStick = newValues;
  68314. },
  68315. enumerable: true,
  68316. configurable: true
  68317. });
  68318. Gamepad.prototype.update = function () {
  68319. if (this._leftStick) {
  68320. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  68321. if (this._invertLeftStickY) {
  68322. this.leftStick.y *= -1;
  68323. }
  68324. }
  68325. if (this._rightStick) {
  68326. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  68327. }
  68328. };
  68329. Gamepad.prototype.dispose = function () {
  68330. };
  68331. Gamepad.GAMEPAD = 0;
  68332. Gamepad.GENERIC = 1;
  68333. Gamepad.XBOX = 2;
  68334. Gamepad.POSE_ENABLED = 3;
  68335. return Gamepad;
  68336. }());
  68337. BABYLON.Gamepad = Gamepad;
  68338. var GenericPad = /** @class */ (function (_super) {
  68339. __extends(GenericPad, _super);
  68340. function GenericPad(id, index, browserGamepad) {
  68341. var _this = _super.call(this, id, index, browserGamepad) || this;
  68342. _this.onButtonDownObservable = new BABYLON.Observable();
  68343. _this.onButtonUpObservable = new BABYLON.Observable();
  68344. _this.type = Gamepad.GENERIC;
  68345. _this._buttons = new Array(browserGamepad.buttons.length);
  68346. return _this;
  68347. }
  68348. GenericPad.prototype.onbuttondown = function (callback) {
  68349. this._onbuttondown = callback;
  68350. };
  68351. GenericPad.prototype.onbuttonup = function (callback) {
  68352. this._onbuttonup = callback;
  68353. };
  68354. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  68355. if (newValue !== currentValue) {
  68356. if (newValue === 1) {
  68357. if (this._onbuttondown) {
  68358. this._onbuttondown(buttonIndex);
  68359. }
  68360. this.onButtonDownObservable.notifyObservers(buttonIndex);
  68361. }
  68362. if (newValue === 0) {
  68363. if (this._onbuttonup) {
  68364. this._onbuttonup(buttonIndex);
  68365. }
  68366. this.onButtonUpObservable.notifyObservers(buttonIndex);
  68367. }
  68368. }
  68369. return newValue;
  68370. };
  68371. GenericPad.prototype.update = function () {
  68372. _super.prototype.update.call(this);
  68373. for (var index = 0; index < this._buttons.length; index++) {
  68374. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  68375. }
  68376. };
  68377. GenericPad.prototype.dispose = function () {
  68378. _super.prototype.dispose.call(this);
  68379. this.onButtonDownObservable.clear();
  68380. this.onButtonUpObservable.clear();
  68381. };
  68382. return GenericPad;
  68383. }(Gamepad));
  68384. BABYLON.GenericPad = GenericPad;
  68385. })(BABYLON || (BABYLON = {}));
  68386. //# sourceMappingURL=babylon.gamepad.js.map
  68387. "use strict";
  68388. var BABYLON;
  68389. (function (BABYLON) {
  68390. var Xbox360Button;
  68391. (function (Xbox360Button) {
  68392. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  68393. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  68394. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  68395. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  68396. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  68397. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  68398. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  68399. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  68400. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  68401. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  68402. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  68403. var Xbox360Dpad;
  68404. (function (Xbox360Dpad) {
  68405. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  68406. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  68407. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  68408. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  68409. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  68410. var Xbox360Pad = /** @class */ (function (_super) {
  68411. __extends(Xbox360Pad, _super);
  68412. function Xbox360Pad(id, index, gamepad, xboxOne) {
  68413. if (xboxOne === void 0) { xboxOne = false; }
  68414. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  68415. _this._leftTrigger = 0;
  68416. _this._rightTrigger = 0;
  68417. _this.onButtonDownObservable = new BABYLON.Observable();
  68418. _this.onButtonUpObservable = new BABYLON.Observable();
  68419. _this.onPadDownObservable = new BABYLON.Observable();
  68420. _this.onPadUpObservable = new BABYLON.Observable();
  68421. _this._buttonA = 0;
  68422. _this._buttonB = 0;
  68423. _this._buttonX = 0;
  68424. _this._buttonY = 0;
  68425. _this._buttonBack = 0;
  68426. _this._buttonStart = 0;
  68427. _this._buttonLB = 0;
  68428. _this._buttonRB = 0;
  68429. _this._buttonLeftStick = 0;
  68430. _this._buttonRightStick = 0;
  68431. _this._dPadUp = 0;
  68432. _this._dPadDown = 0;
  68433. _this._dPadLeft = 0;
  68434. _this._dPadRight = 0;
  68435. _this._isXboxOnePad = false;
  68436. _this.type = BABYLON.Gamepad.XBOX;
  68437. _this._isXboxOnePad = xboxOne;
  68438. return _this;
  68439. }
  68440. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  68441. this._onlefttriggerchanged = callback;
  68442. };
  68443. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  68444. this._onrighttriggerchanged = callback;
  68445. };
  68446. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  68447. get: function () {
  68448. return this._leftTrigger;
  68449. },
  68450. set: function (newValue) {
  68451. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  68452. this._onlefttriggerchanged(newValue);
  68453. }
  68454. this._leftTrigger = newValue;
  68455. },
  68456. enumerable: true,
  68457. configurable: true
  68458. });
  68459. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  68460. get: function () {
  68461. return this._rightTrigger;
  68462. },
  68463. set: function (newValue) {
  68464. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  68465. this._onrighttriggerchanged(newValue);
  68466. }
  68467. this._rightTrigger = newValue;
  68468. },
  68469. enumerable: true,
  68470. configurable: true
  68471. });
  68472. Xbox360Pad.prototype.onbuttondown = function (callback) {
  68473. this._onbuttondown = callback;
  68474. };
  68475. Xbox360Pad.prototype.onbuttonup = function (callback) {
  68476. this._onbuttonup = callback;
  68477. };
  68478. Xbox360Pad.prototype.ondpaddown = function (callback) {
  68479. this._ondpaddown = callback;
  68480. };
  68481. Xbox360Pad.prototype.ondpadup = function (callback) {
  68482. this._ondpadup = callback;
  68483. };
  68484. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  68485. if (newValue !== currentValue) {
  68486. if (newValue === 1) {
  68487. if (this._onbuttondown) {
  68488. this._onbuttondown(buttonType);
  68489. }
  68490. this.onButtonDownObservable.notifyObservers(buttonType);
  68491. }
  68492. if (newValue === 0) {
  68493. if (this._onbuttonup) {
  68494. this._onbuttonup(buttonType);
  68495. }
  68496. this.onButtonUpObservable.notifyObservers(buttonType);
  68497. }
  68498. }
  68499. return newValue;
  68500. };
  68501. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  68502. if (newValue !== currentValue) {
  68503. if (newValue === 1) {
  68504. if (this._ondpaddown) {
  68505. this._ondpaddown(buttonType);
  68506. }
  68507. this.onPadDownObservable.notifyObservers(buttonType);
  68508. }
  68509. if (newValue === 0) {
  68510. if (this._ondpadup) {
  68511. this._ondpadup(buttonType);
  68512. }
  68513. this.onPadUpObservable.notifyObservers(buttonType);
  68514. }
  68515. }
  68516. return newValue;
  68517. };
  68518. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  68519. get: function () {
  68520. return this._buttonA;
  68521. },
  68522. set: function (value) {
  68523. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  68524. },
  68525. enumerable: true,
  68526. configurable: true
  68527. });
  68528. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  68529. get: function () {
  68530. return this._buttonB;
  68531. },
  68532. set: function (value) {
  68533. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  68534. },
  68535. enumerable: true,
  68536. configurable: true
  68537. });
  68538. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  68539. get: function () {
  68540. return this._buttonX;
  68541. },
  68542. set: function (value) {
  68543. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  68544. },
  68545. enumerable: true,
  68546. configurable: true
  68547. });
  68548. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  68549. get: function () {
  68550. return this._buttonY;
  68551. },
  68552. set: function (value) {
  68553. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  68554. },
  68555. enumerable: true,
  68556. configurable: true
  68557. });
  68558. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  68559. get: function () {
  68560. return this._buttonStart;
  68561. },
  68562. set: function (value) {
  68563. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  68564. },
  68565. enumerable: true,
  68566. configurable: true
  68567. });
  68568. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  68569. get: function () {
  68570. return this._buttonBack;
  68571. },
  68572. set: function (value) {
  68573. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  68574. },
  68575. enumerable: true,
  68576. configurable: true
  68577. });
  68578. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  68579. get: function () {
  68580. return this._buttonLB;
  68581. },
  68582. set: function (value) {
  68583. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  68584. },
  68585. enumerable: true,
  68586. configurable: true
  68587. });
  68588. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  68589. get: function () {
  68590. return this._buttonRB;
  68591. },
  68592. set: function (value) {
  68593. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  68594. },
  68595. enumerable: true,
  68596. configurable: true
  68597. });
  68598. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  68599. get: function () {
  68600. return this._buttonLeftStick;
  68601. },
  68602. set: function (value) {
  68603. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  68604. },
  68605. enumerable: true,
  68606. configurable: true
  68607. });
  68608. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  68609. get: function () {
  68610. return this._buttonRightStick;
  68611. },
  68612. set: function (value) {
  68613. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  68614. },
  68615. enumerable: true,
  68616. configurable: true
  68617. });
  68618. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  68619. get: function () {
  68620. return this._dPadUp;
  68621. },
  68622. set: function (value) {
  68623. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  68624. },
  68625. enumerable: true,
  68626. configurable: true
  68627. });
  68628. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  68629. get: function () {
  68630. return this._dPadDown;
  68631. },
  68632. set: function (value) {
  68633. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  68634. },
  68635. enumerable: true,
  68636. configurable: true
  68637. });
  68638. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  68639. get: function () {
  68640. return this._dPadLeft;
  68641. },
  68642. set: function (value) {
  68643. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  68644. },
  68645. enumerable: true,
  68646. configurable: true
  68647. });
  68648. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  68649. get: function () {
  68650. return this._dPadRight;
  68651. },
  68652. set: function (value) {
  68653. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  68654. },
  68655. enumerable: true,
  68656. configurable: true
  68657. });
  68658. Xbox360Pad.prototype.update = function () {
  68659. _super.prototype.update.call(this);
  68660. if (this._isXboxOnePad) {
  68661. this.buttonA = this.browserGamepad.buttons[0].value;
  68662. this.buttonB = this.browserGamepad.buttons[1].value;
  68663. this.buttonX = this.browserGamepad.buttons[2].value;
  68664. this.buttonY = this.browserGamepad.buttons[3].value;
  68665. this.buttonLB = this.browserGamepad.buttons[4].value;
  68666. this.buttonRB = this.browserGamepad.buttons[5].value;
  68667. this.leftTrigger = this.browserGamepad.axes[2];
  68668. this.rightTrigger = this.browserGamepad.axes[5];
  68669. this.buttonBack = this.browserGamepad.buttons[9].value;
  68670. this.buttonStart = this.browserGamepad.buttons[8].value;
  68671. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  68672. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  68673. this.dPadUp = this.browserGamepad.buttons[11].value;
  68674. this.dPadDown = this.browserGamepad.buttons[12].value;
  68675. this.dPadLeft = this.browserGamepad.buttons[13].value;
  68676. this.dPadRight = this.browserGamepad.buttons[14].value;
  68677. }
  68678. else {
  68679. this.buttonA = this.browserGamepad.buttons[0].value;
  68680. this.buttonB = this.browserGamepad.buttons[1].value;
  68681. this.buttonX = this.browserGamepad.buttons[2].value;
  68682. this.buttonY = this.browserGamepad.buttons[3].value;
  68683. this.buttonLB = this.browserGamepad.buttons[4].value;
  68684. this.buttonRB = this.browserGamepad.buttons[5].value;
  68685. this.leftTrigger = this.browserGamepad.buttons[6].value;
  68686. this.rightTrigger = this.browserGamepad.buttons[7].value;
  68687. this.buttonBack = this.browserGamepad.buttons[8].value;
  68688. this.buttonStart = this.browserGamepad.buttons[9].value;
  68689. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  68690. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  68691. this.dPadUp = this.browserGamepad.buttons[12].value;
  68692. this.dPadDown = this.browserGamepad.buttons[13].value;
  68693. this.dPadLeft = this.browserGamepad.buttons[14].value;
  68694. this.dPadRight = this.browserGamepad.buttons[15].value;
  68695. }
  68696. };
  68697. Xbox360Pad.prototype.dispose = function () {
  68698. _super.prototype.dispose.call(this);
  68699. this.onButtonDownObservable.clear();
  68700. this.onButtonUpObservable.clear();
  68701. this.onPadDownObservable.clear();
  68702. this.onPadUpObservable.clear();
  68703. };
  68704. return Xbox360Pad;
  68705. }(BABYLON.Gamepad));
  68706. BABYLON.Xbox360Pad = Xbox360Pad;
  68707. })(BABYLON || (BABYLON = {}));
  68708. //# sourceMappingURL=babylon.xboxGamepad.js.map
  68709. "use strict";
  68710. var BABYLON;
  68711. (function (BABYLON) {
  68712. /**
  68713. * Defines the types of pose enabled controllers that are supported
  68714. */
  68715. var PoseEnabledControllerType;
  68716. (function (PoseEnabledControllerType) {
  68717. /**
  68718. * HTC Vive
  68719. */
  68720. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  68721. /**
  68722. * Oculus Rift
  68723. */
  68724. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  68725. /**
  68726. * Windows mixed reality
  68727. */
  68728. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  68729. /**
  68730. * Samsung gear VR
  68731. */
  68732. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  68733. /**
  68734. * Google Daydream
  68735. */
  68736. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  68737. /**
  68738. * Generic
  68739. */
  68740. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  68741. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  68742. /**
  68743. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  68744. */
  68745. var PoseEnabledControllerHelper = /** @class */ (function () {
  68746. function PoseEnabledControllerHelper() {
  68747. }
  68748. /**
  68749. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  68750. * @param vrGamepad the gamepad to initialized
  68751. * @returns a vr controller of the type the gamepad identified as
  68752. */
  68753. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  68754. // Oculus Touch
  68755. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  68756. return new BABYLON.OculusTouchController(vrGamepad);
  68757. }
  68758. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  68759. return new BABYLON.WindowsMotionController(vrGamepad);
  68760. }
  68761. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  68762. return new BABYLON.ViveController(vrGamepad);
  68763. }
  68764. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  68765. return new BABYLON.GearVRController(vrGamepad);
  68766. }
  68767. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  68768. return new BABYLON.DaydreamController(vrGamepad);
  68769. }
  68770. else {
  68771. return new BABYLON.GenericController(vrGamepad);
  68772. }
  68773. };
  68774. return PoseEnabledControllerHelper;
  68775. }());
  68776. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  68777. /**
  68778. * Defines the PoseEnabledController object that contains state of a vr capable controller
  68779. */
  68780. var PoseEnabledController = /** @class */ (function (_super) {
  68781. __extends(PoseEnabledController, _super);
  68782. /**
  68783. * Creates a new PoseEnabledController from a gamepad
  68784. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  68785. */
  68786. function PoseEnabledController(browserGamepad) {
  68787. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  68788. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  68789. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  68790. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  68791. /**
  68792. * The device position in babylon space
  68793. */
  68794. _this.devicePosition = BABYLON.Vector3.Zero();
  68795. /**
  68796. * The device rotation in babylon space
  68797. */
  68798. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  68799. /**
  68800. * The scale factor of the device in babylon space
  68801. */
  68802. _this.deviceScaleFactor = 1;
  68803. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  68804. /**
  68805. * Internal, matrix used to convert room space to babylon space
  68806. */
  68807. _this._deviceToWorld = BABYLON.Matrix.Identity();
  68808. /**
  68809. * Node to be used when casting a ray from the controller
  68810. */
  68811. _this._pointingPoseNode = null;
  68812. _this._workingMatrix = BABYLON.Matrix.Identity();
  68813. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  68814. _this.controllerType = PoseEnabledControllerType.GENERIC;
  68815. _this.position = BABYLON.Vector3.Zero();
  68816. _this.rotationQuaternion = new BABYLON.Quaternion();
  68817. _this._calculatedPosition = BABYLON.Vector3.Zero();
  68818. _this._calculatedRotation = new BABYLON.Quaternion();
  68819. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  68820. return _this;
  68821. }
  68822. /**
  68823. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  68824. */
  68825. PoseEnabledController.prototype.update = function () {
  68826. _super.prototype.update.call(this);
  68827. var pose = this.browserGamepad.pose;
  68828. this.updateFromDevice(pose);
  68829. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  68830. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  68831. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  68832. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  68833. if (this._mesh) {
  68834. this._mesh.position.copyFrom(this.devicePosition);
  68835. if (this._mesh.rotationQuaternion) {
  68836. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  68837. }
  68838. }
  68839. };
  68840. /**
  68841. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  68842. * @param poseData raw pose fromthe device
  68843. */
  68844. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  68845. if (poseData) {
  68846. this.rawPose = poseData;
  68847. if (poseData.position) {
  68848. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  68849. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  68850. this._deviceRoomPosition.z *= -1;
  68851. }
  68852. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  68853. this._calculatedPosition.addInPlace(this.position);
  68854. }
  68855. var pose = this.rawPose;
  68856. if (poseData.orientation && pose.orientation) {
  68857. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  68858. if (this._mesh) {
  68859. if (this._mesh.getScene().useRightHandedSystem) {
  68860. this._deviceRoomRotationQuaternion.z *= -1;
  68861. this._deviceRoomRotationQuaternion.w *= -1;
  68862. }
  68863. else {
  68864. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  68865. }
  68866. }
  68867. // if the camera is set, rotate to the camera's rotation
  68868. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  68869. }
  68870. }
  68871. };
  68872. /**
  68873. * Attaches a mesh to the controller
  68874. * @param mesh the mesh to be attached
  68875. */
  68876. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  68877. if (this._mesh) {
  68878. this._mesh.parent = null;
  68879. }
  68880. this._mesh = mesh;
  68881. if (this._poseControlledCamera) {
  68882. this._mesh.parent = this._poseControlledCamera;
  68883. }
  68884. if (!this._mesh.rotationQuaternion) {
  68885. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  68886. }
  68887. };
  68888. /**
  68889. * Attaches the controllers mesh to a camera
  68890. * @param camera the camera the mesh should be attached to
  68891. */
  68892. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  68893. this._poseControlledCamera = camera;
  68894. if (this._mesh) {
  68895. this._mesh.parent = this._poseControlledCamera;
  68896. }
  68897. };
  68898. /**
  68899. * Disposes of the controller
  68900. */
  68901. PoseEnabledController.prototype.dispose = function () {
  68902. if (this._mesh) {
  68903. this._mesh.dispose();
  68904. }
  68905. this._mesh = null;
  68906. _super.prototype.dispose.call(this);
  68907. };
  68908. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  68909. /**
  68910. * The mesh that is attached to the controller
  68911. */
  68912. get: function () {
  68913. return this._mesh;
  68914. },
  68915. enumerable: true,
  68916. configurable: true
  68917. });
  68918. /**
  68919. * Gets the ray of the controller in the direction the controller is pointing
  68920. * @param length the length the resulting ray should be
  68921. * @returns a ray in the direction the controller is pointing
  68922. */
  68923. PoseEnabledController.prototype.getForwardRay = function (length) {
  68924. if (length === void 0) { length = 100; }
  68925. if (!this.mesh) {
  68926. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  68927. }
  68928. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  68929. var origin = m.getTranslation();
  68930. var forward = new BABYLON.Vector3(0, 0, -1);
  68931. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  68932. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  68933. return new BABYLON.Ray(origin, direction, length);
  68934. };
  68935. /**
  68936. * Name of the child mesh that can be used to cast a ray from the controller
  68937. */
  68938. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  68939. return PoseEnabledController;
  68940. }(BABYLON.Gamepad));
  68941. BABYLON.PoseEnabledController = PoseEnabledController;
  68942. })(BABYLON || (BABYLON = {}));
  68943. //# sourceMappingURL=babylon.poseEnabledController.js.map
  68944. "use strict";
  68945. var BABYLON;
  68946. (function (BABYLON) {
  68947. /**
  68948. * Defines the WebVRController object that represents controllers tracked in 3D space
  68949. */
  68950. var WebVRController = /** @class */ (function (_super) {
  68951. __extends(WebVRController, _super);
  68952. /**
  68953. * Creates a new WebVRController from a gamepad
  68954. * @param vrGamepad the gamepad that the WebVRController should be created from
  68955. */
  68956. function WebVRController(vrGamepad) {
  68957. var _this = _super.call(this, vrGamepad) || this;
  68958. // Observables
  68959. /**
  68960. * Fired when the trigger state has changed
  68961. */
  68962. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  68963. /**
  68964. * Fired when the main button state has changed
  68965. */
  68966. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  68967. /**
  68968. * Fired when the secondary button state has changed
  68969. */
  68970. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  68971. /**
  68972. * Fired when the pad state has changed
  68973. */
  68974. _this.onPadStateChangedObservable = new BABYLON.Observable();
  68975. /**
  68976. * Fired when controllers stick values have changed
  68977. */
  68978. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  68979. /**
  68980. * X and Y axis corrisponding to the controllers joystick
  68981. */
  68982. _this.pad = { x: 0, y: 0 };
  68983. // avoid GC, store state in a tmp object
  68984. _this._changes = {
  68985. pressChanged: false,
  68986. touchChanged: false,
  68987. valueChanged: false,
  68988. changed: false
  68989. };
  68990. _this._buttons = new Array(vrGamepad.buttons.length);
  68991. _this.hand = vrGamepad.hand;
  68992. return _this;
  68993. }
  68994. /**
  68995. * Fired when a controller button's state has changed
  68996. * @param callback the callback containing the button that was modified
  68997. */
  68998. WebVRController.prototype.onButtonStateChange = function (callback) {
  68999. this._onButtonStateChange = callback;
  69000. };
  69001. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  69002. /**
  69003. * The default controller model for the controller
  69004. */
  69005. get: function () {
  69006. return this._defaultModel;
  69007. },
  69008. enumerable: true,
  69009. configurable: true
  69010. });
  69011. /**
  69012. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  69013. */
  69014. WebVRController.prototype.update = function () {
  69015. _super.prototype.update.call(this);
  69016. for (var index = 0; index < this._buttons.length; index++) {
  69017. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  69018. }
  69019. ;
  69020. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  69021. this.pad.x = this.leftStick.x;
  69022. this.pad.y = this.leftStick.y;
  69023. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  69024. }
  69025. };
  69026. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  69027. if (!newState) {
  69028. newState = {
  69029. pressed: false,
  69030. touched: false,
  69031. value: 0
  69032. };
  69033. }
  69034. if (!currentState) {
  69035. this._buttons[buttonIndex] = {
  69036. pressed: newState.pressed,
  69037. touched: newState.touched,
  69038. value: newState.value
  69039. };
  69040. return;
  69041. }
  69042. this._checkChanges(newState, currentState);
  69043. if (this._changes.changed) {
  69044. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  69045. this._handleButtonChange(buttonIndex, newState, this._changes);
  69046. }
  69047. this._buttons[buttonIndex].pressed = newState.pressed;
  69048. this._buttons[buttonIndex].touched = newState.touched;
  69049. // oculus triggers are never 0, thou not touched.
  69050. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  69051. };
  69052. WebVRController.prototype._checkChanges = function (newState, currentState) {
  69053. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  69054. this._changes.touchChanged = newState.touched !== currentState.touched;
  69055. this._changes.valueChanged = newState.value !== currentState.value;
  69056. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  69057. return this._changes;
  69058. };
  69059. /**
  69060. * Disposes of th webVRCOntroller
  69061. */
  69062. WebVRController.prototype.dispose = function () {
  69063. _super.prototype.dispose.call(this);
  69064. this.onTriggerStateChangedObservable.clear();
  69065. this.onMainButtonStateChangedObservable.clear();
  69066. this.onSecondaryButtonStateChangedObservable.clear();
  69067. this.onPadStateChangedObservable.clear();
  69068. this.onPadValuesChangedObservable.clear();
  69069. };
  69070. return WebVRController;
  69071. }(BABYLON.PoseEnabledController));
  69072. BABYLON.WebVRController = WebVRController;
  69073. })(BABYLON || (BABYLON = {}));
  69074. //# sourceMappingURL=babylon.webVRController.js.map
  69075. "use strict";
  69076. var BABYLON;
  69077. (function (BABYLON) {
  69078. /**
  69079. * Oculus Touch Controller
  69080. */
  69081. var OculusTouchController = /** @class */ (function (_super) {
  69082. __extends(OculusTouchController, _super);
  69083. /**
  69084. * Creates a new OculusTouchController from a gamepad
  69085. * @param vrGamepad the gamepad that the controller should be created from
  69086. */
  69087. function OculusTouchController(vrGamepad) {
  69088. var _this = _super.call(this, vrGamepad) || this;
  69089. /**
  69090. * Fired when the secondary trigger on this controller is modified
  69091. */
  69092. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  69093. /**
  69094. * Fired when the thumb rest on this controller is modified
  69095. */
  69096. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  69097. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  69098. return _this;
  69099. }
  69100. /**
  69101. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  69102. * @param scene scene in which to add meshes
  69103. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  69104. */
  69105. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  69106. var _this = this;
  69107. var meshName;
  69108. // Hand
  69109. if (this.hand === 'left') {
  69110. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  69111. }
  69112. else {
  69113. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  69114. }
  69115. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  69116. /*
  69117. Parent Mesh name: oculus_touch_left
  69118. - body
  69119. - trigger
  69120. - thumbstick
  69121. - grip
  69122. - button_y
  69123. - button_x
  69124. - button_enter
  69125. */
  69126. _this._defaultModel = newMeshes[1];
  69127. _this.attachToMesh(_this._defaultModel);
  69128. if (meshLoaded) {
  69129. meshLoaded(_this._defaultModel);
  69130. }
  69131. });
  69132. };
  69133. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  69134. /**
  69135. * Fired when the A button on this controller is modified
  69136. */
  69137. get: function () {
  69138. if (this.hand === 'right') {
  69139. return this.onMainButtonStateChangedObservable;
  69140. }
  69141. else {
  69142. throw new Error('No A button on left hand');
  69143. }
  69144. },
  69145. enumerable: true,
  69146. configurable: true
  69147. });
  69148. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  69149. /**
  69150. * Fired when the B button on this controller is modified
  69151. */
  69152. get: function () {
  69153. if (this.hand === 'right') {
  69154. return this.onSecondaryButtonStateChangedObservable;
  69155. }
  69156. else {
  69157. throw new Error('No B button on left hand');
  69158. }
  69159. },
  69160. enumerable: true,
  69161. configurable: true
  69162. });
  69163. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  69164. /**
  69165. * Fired when the X button on this controller is modified
  69166. */
  69167. get: function () {
  69168. if (this.hand === 'left') {
  69169. return this.onMainButtonStateChangedObservable;
  69170. }
  69171. else {
  69172. throw new Error('No X button on right hand');
  69173. }
  69174. },
  69175. enumerable: true,
  69176. configurable: true
  69177. });
  69178. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  69179. /**
  69180. * Fired when the Y button on this controller is modified
  69181. */
  69182. get: function () {
  69183. if (this.hand === 'left') {
  69184. return this.onSecondaryButtonStateChangedObservable;
  69185. }
  69186. else {
  69187. throw new Error('No Y button on right hand');
  69188. }
  69189. },
  69190. enumerable: true,
  69191. configurable: true
  69192. });
  69193. /**
  69194. * Called once for each button that changed state since the last frame
  69195. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  69196. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  69197. * 2) secondary trigger (same)
  69198. * 3) A (right) X (left), touch, pressed = value
  69199. * 4) B / Y
  69200. * 5) thumb rest
  69201. * @param buttonIdx Which button index changed
  69202. * @param state New state of the button
  69203. * @param changes Which properties on the state changed since last frame
  69204. */
  69205. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  69206. var notifyObject = state; //{ state: state, changes: changes };
  69207. var triggerDirection = this.hand === 'right' ? -1 : 1;
  69208. switch (buttonIdx) {
  69209. case 0:
  69210. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  69211. return;
  69212. case 1:// index trigger
  69213. if (this._defaultModel) {
  69214. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  69215. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  69216. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  69217. }
  69218. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  69219. return;
  69220. case 2:// secondary trigger
  69221. if (this._defaultModel) {
  69222. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  69223. }
  69224. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  69225. return;
  69226. case 3:
  69227. if (this._defaultModel) {
  69228. if (notifyObject.pressed) {
  69229. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  69230. }
  69231. else {
  69232. (this._defaultModel.getChildren()[1]).position.y = 0;
  69233. }
  69234. }
  69235. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  69236. return;
  69237. case 4:
  69238. if (this._defaultModel) {
  69239. if (notifyObject.pressed) {
  69240. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  69241. }
  69242. else {
  69243. (this._defaultModel.getChildren()[2]).position.y = 0;
  69244. }
  69245. }
  69246. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  69247. return;
  69248. case 5:
  69249. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  69250. return;
  69251. }
  69252. };
  69253. /**
  69254. * Base Url for the controller model.
  69255. */
  69256. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  69257. /**
  69258. * File name for the left controller model.
  69259. */
  69260. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  69261. /**
  69262. * File name for the right controller model.
  69263. */
  69264. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  69265. return OculusTouchController;
  69266. }(BABYLON.WebVRController));
  69267. BABYLON.OculusTouchController = OculusTouchController;
  69268. })(BABYLON || (BABYLON = {}));
  69269. //# sourceMappingURL=babylon.oculusTouchController.js.map
  69270. "use strict";
  69271. var BABYLON;
  69272. (function (BABYLON) {
  69273. /**
  69274. * Vive Controller
  69275. */
  69276. var ViveController = /** @class */ (function (_super) {
  69277. __extends(ViveController, _super);
  69278. /**
  69279. * Creates a new ViveController from a gamepad
  69280. * @param vrGamepad the gamepad that the controller should be created from
  69281. */
  69282. function ViveController(vrGamepad) {
  69283. var _this = _super.call(this, vrGamepad) || this;
  69284. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  69285. _this._invertLeftStickY = true;
  69286. return _this;
  69287. }
  69288. /**
  69289. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  69290. * @param scene scene in which to add meshes
  69291. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  69292. */
  69293. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  69294. var _this = this;
  69295. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  69296. /*
  69297. Parent Mesh name: ViveWand
  69298. - body
  69299. - r_gripper
  69300. - l_gripper
  69301. - menu_button
  69302. - system_button
  69303. - trackpad
  69304. - trigger
  69305. - LED
  69306. */
  69307. _this._defaultModel = newMeshes[1];
  69308. _this.attachToMesh(_this._defaultModel);
  69309. if (meshLoaded) {
  69310. meshLoaded(_this._defaultModel);
  69311. }
  69312. });
  69313. };
  69314. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  69315. /**
  69316. * Fired when the left button on this controller is modified
  69317. */
  69318. get: function () {
  69319. return this.onMainButtonStateChangedObservable;
  69320. },
  69321. enumerable: true,
  69322. configurable: true
  69323. });
  69324. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  69325. /**
  69326. * Fired when the right button on this controller is modified
  69327. */
  69328. get: function () {
  69329. return this.onMainButtonStateChangedObservable;
  69330. },
  69331. enumerable: true,
  69332. configurable: true
  69333. });
  69334. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  69335. /**
  69336. * Fired when the menu button on this controller is modified
  69337. */
  69338. get: function () {
  69339. return this.onSecondaryButtonStateChangedObservable;
  69340. },
  69341. enumerable: true,
  69342. configurable: true
  69343. });
  69344. /**
  69345. * Called once for each button that changed state since the last frame
  69346. * Vive mapping:
  69347. * 0: touchpad
  69348. * 1: trigger
  69349. * 2: left AND right buttons
  69350. * 3: menu button
  69351. * @param buttonIdx Which button index changed
  69352. * @param state New state of the button
  69353. * @param changes Which properties on the state changed since last frame
  69354. */
  69355. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  69356. var notifyObject = state; //{ state: state, changes: changes };
  69357. switch (buttonIdx) {
  69358. case 0:
  69359. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  69360. return;
  69361. case 1:// index trigger
  69362. if (this._defaultModel) {
  69363. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  69364. }
  69365. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  69366. return;
  69367. case 2:// left AND right button
  69368. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  69369. return;
  69370. case 3:
  69371. if (this._defaultModel) {
  69372. if (notifyObject.pressed) {
  69373. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  69374. }
  69375. else {
  69376. (this._defaultModel.getChildren()[2]).position.y = 0;
  69377. }
  69378. }
  69379. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  69380. return;
  69381. }
  69382. };
  69383. /**
  69384. * Base Url for the controller model.
  69385. */
  69386. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  69387. /**
  69388. * File name for the controller model.
  69389. */
  69390. ViveController.MODEL_FILENAME = 'wand.babylon';
  69391. return ViveController;
  69392. }(BABYLON.WebVRController));
  69393. BABYLON.ViveController = ViveController;
  69394. })(BABYLON || (BABYLON = {}));
  69395. //# sourceMappingURL=babylon.viveController.js.map
  69396. "use strict";
  69397. var BABYLON;
  69398. (function (BABYLON) {
  69399. /**
  69400. * Generic Controller
  69401. */
  69402. var GenericController = /** @class */ (function (_super) {
  69403. __extends(GenericController, _super);
  69404. /**
  69405. * Creates a new GenericController from a gamepad
  69406. * @param vrGamepad the gamepad that the controller should be created from
  69407. */
  69408. function GenericController(vrGamepad) {
  69409. return _super.call(this, vrGamepad) || this;
  69410. }
  69411. /**
  69412. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  69413. * @param scene scene in which to add meshes
  69414. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  69415. */
  69416. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  69417. var _this = this;
  69418. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  69419. _this._defaultModel = newMeshes[1];
  69420. _this.attachToMesh(_this._defaultModel);
  69421. if (meshLoaded) {
  69422. meshLoaded(_this._defaultModel);
  69423. }
  69424. });
  69425. };
  69426. /**
  69427. * Called once for each button that changed state since the last frame
  69428. * @param buttonIdx Which button index changed
  69429. * @param state New state of the button
  69430. * @param changes Which properties on the state changed since last frame
  69431. */
  69432. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  69433. console.log("Button id: " + buttonIdx + "state: ");
  69434. console.dir(state);
  69435. };
  69436. /**
  69437. * Base Url for the controller model.
  69438. */
  69439. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  69440. /**
  69441. * File name for the controller model.
  69442. */
  69443. GenericController.MODEL_FILENAME = 'generic.babylon';
  69444. return GenericController;
  69445. }(BABYLON.WebVRController));
  69446. BABYLON.GenericController = GenericController;
  69447. })(BABYLON || (BABYLON = {}));
  69448. //# sourceMappingURL=babylon.genericController.js.map
  69449. "use strict";
  69450. var BABYLON;
  69451. (function (BABYLON) {
  69452. /**
  69453. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  69454. */
  69455. var LoadedMeshInfo = /** @class */ (function () {
  69456. function LoadedMeshInfo() {
  69457. /**
  69458. * Map of the button meshes contained in the controller
  69459. */
  69460. this.buttonMeshes = {};
  69461. /**
  69462. * Map of the axis meshes contained in the controller
  69463. */
  69464. this.axisMeshes = {};
  69465. }
  69466. return LoadedMeshInfo;
  69467. }());
  69468. /**
  69469. * Defines the WindowsMotionController object that the state of the windows motion controller
  69470. */
  69471. var WindowsMotionController = /** @class */ (function (_super) {
  69472. __extends(WindowsMotionController, _super);
  69473. /**
  69474. * Creates a new WindowsMotionController from a gamepad
  69475. * @param vrGamepad the gamepad that the controller should be created from
  69476. */
  69477. function WindowsMotionController(vrGamepad) {
  69478. var _this = _super.call(this, vrGamepad) || this;
  69479. _this._mapping = {
  69480. // Semantic button names
  69481. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  69482. // A mapping of the button name to glTF model node name
  69483. // that should be transformed by button value.
  69484. buttonMeshNames: {
  69485. 'trigger': 'SELECT',
  69486. 'menu': 'MENU',
  69487. 'grip': 'GRASP',
  69488. 'thumbstick': 'THUMBSTICK_PRESS',
  69489. 'trackpad': 'TOUCHPAD_PRESS'
  69490. },
  69491. // This mapping is used to translate from the Motion Controller to Babylon semantics
  69492. buttonObservableNames: {
  69493. 'trigger': 'onTriggerStateChangedObservable',
  69494. 'menu': 'onSecondaryButtonStateChangedObservable',
  69495. 'grip': 'onMainButtonStateChangedObservable',
  69496. 'thumbstick': 'onPadStateChangedObservable',
  69497. 'trackpad': 'onTrackpadChangedObservable'
  69498. },
  69499. // A mapping of the axis name to glTF model node name
  69500. // that should be transformed by axis value.
  69501. // This array mirrors the browserGamepad.axes array, such that
  69502. // the mesh corresponding to axis 0 is in this array index 0.
  69503. axisMeshNames: [
  69504. 'THUMBSTICK_X',
  69505. 'THUMBSTICK_Y',
  69506. 'TOUCHPAD_TOUCH_X',
  69507. 'TOUCHPAD_TOUCH_Y'
  69508. ],
  69509. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  69510. };
  69511. /**
  69512. * Fired when the trackpad on this controller is clicked
  69513. */
  69514. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  69515. /**
  69516. * Fired when the trackpad on this controller is modified
  69517. */
  69518. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  69519. /**
  69520. * The current x and y values of this controller's trackpad
  69521. */
  69522. _this.trackpad = { x: 0, y: 0 };
  69523. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  69524. _this._loadedMeshInfo = null;
  69525. return _this;
  69526. }
  69527. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  69528. /**
  69529. * Fired when the trigger on this controller is modified
  69530. */
  69531. get: function () {
  69532. return this.onTriggerStateChangedObservable;
  69533. },
  69534. enumerable: true,
  69535. configurable: true
  69536. });
  69537. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  69538. /**
  69539. * Fired when the menu button on this controller is modified
  69540. */
  69541. get: function () {
  69542. return this.onSecondaryButtonStateChangedObservable;
  69543. },
  69544. enumerable: true,
  69545. configurable: true
  69546. });
  69547. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  69548. /**
  69549. * Fired when the grip button on this controller is modified
  69550. */
  69551. get: function () {
  69552. return this.onMainButtonStateChangedObservable;
  69553. },
  69554. enumerable: true,
  69555. configurable: true
  69556. });
  69557. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  69558. /**
  69559. * Fired when the thumbstick button on this controller is modified
  69560. */
  69561. get: function () {
  69562. return this.onPadStateChangedObservable;
  69563. },
  69564. enumerable: true,
  69565. configurable: true
  69566. });
  69567. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  69568. /**
  69569. * Fired when the touchpad button on this controller is modified
  69570. */
  69571. get: function () {
  69572. return this.onTrackpadChangedObservable;
  69573. },
  69574. enumerable: true,
  69575. configurable: true
  69576. });
  69577. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  69578. /**
  69579. * Fired when the touchpad values on this controller are modified
  69580. */
  69581. get: function () {
  69582. return this.onTrackpadValuesChangedObservable;
  69583. },
  69584. enumerable: true,
  69585. configurable: true
  69586. });
  69587. /**
  69588. * Called once per frame by the engine.
  69589. */
  69590. WindowsMotionController.prototype.update = function () {
  69591. _super.prototype.update.call(this);
  69592. if (this.browserGamepad.axes) {
  69593. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  69594. this.trackpad.x = this.browserGamepad["axes"][2];
  69595. this.trackpad.y = this.browserGamepad["axes"][3];
  69596. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  69597. }
  69598. // Only need to animate axes if there is a loaded mesh
  69599. if (this._loadedMeshInfo) {
  69600. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  69601. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  69602. }
  69603. }
  69604. }
  69605. };
  69606. /**
  69607. * Called once for each button that changed state since the last frame
  69608. * @param buttonIdx Which button index changed
  69609. * @param state New state of the button
  69610. * @param changes Which properties on the state changed since last frame
  69611. */
  69612. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  69613. var buttonName = this._mapping.buttons[buttonIdx];
  69614. if (!buttonName) {
  69615. return;
  69616. }
  69617. // Only emit events for buttons that we know how to map from index to name
  69618. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  69619. if (observable) {
  69620. observable.notifyObservers(state);
  69621. }
  69622. this._lerpButtonTransform(buttonName, state.value);
  69623. };
  69624. /**
  69625. * Moves the buttons on the controller mesh based on their current state
  69626. * @param buttonName the name of the button to move
  69627. * @param buttonValue the value of the button which determines the buttons new position
  69628. */
  69629. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  69630. // If there is no loaded mesh, there is nothing to transform.
  69631. if (!this._loadedMeshInfo) {
  69632. return;
  69633. }
  69634. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  69635. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  69636. return;
  69637. }
  69638. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  69639. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  69640. };
  69641. /**
  69642. * Moves the axis on the controller mesh based on its current state
  69643. * @param axis the index of the axis
  69644. * @param axisValue the value of the axis which determines the meshes new position
  69645. * @ignore
  69646. */
  69647. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  69648. if (!this._loadedMeshInfo) {
  69649. return;
  69650. }
  69651. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  69652. if (!meshInfo) {
  69653. return;
  69654. }
  69655. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  69656. return;
  69657. }
  69658. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  69659. var lerpValue = axisValue * 0.5 + 0.5;
  69660. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  69661. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  69662. };
  69663. /**
  69664. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  69665. * @param scene scene in which to add meshes
  69666. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  69667. */
  69668. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  69669. var _this = this;
  69670. if (forceDefault === void 0) { forceDefault = false; }
  69671. var path;
  69672. var filename;
  69673. // Checking if GLB loader is present
  69674. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  69675. // Determine the device specific folder based on the ID suffix
  69676. var device = 'default';
  69677. if (this.id && !forceDefault) {
  69678. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  69679. device = ((match && match[0]) || device);
  69680. }
  69681. // Hand
  69682. if (this.hand === 'left') {
  69683. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  69684. }
  69685. else {
  69686. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  69687. }
  69688. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  69689. }
  69690. else {
  69691. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  69692. path = BABYLON.GenericController.MODEL_BASE_URL;
  69693. filename = BABYLON.GenericController.MODEL_FILENAME;
  69694. }
  69695. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  69696. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  69697. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  69698. if (!_this._loadedMeshInfo) {
  69699. return;
  69700. }
  69701. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  69702. _this.attachToMesh(_this._defaultModel);
  69703. if (meshLoaded) {
  69704. meshLoaded(_this._defaultModel);
  69705. }
  69706. }, null, function (scene, message) {
  69707. BABYLON.Tools.Log(message);
  69708. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  69709. if (!forceDefault) {
  69710. _this.initControllerMesh(scene, meshLoaded, true);
  69711. }
  69712. });
  69713. };
  69714. /**
  69715. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  69716. * can be transformed by button presses and axes values, based on this._mapping.
  69717. *
  69718. * @param scene scene in which the meshes exist
  69719. * @param meshes list of meshes that make up the controller model to process
  69720. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  69721. */
  69722. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  69723. var loadedMeshInfo = null;
  69724. // Create a new mesh to contain the glTF hierarchy
  69725. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  69726. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  69727. var childMesh = null;
  69728. for (var i = 0; i < meshes.length; i++) {
  69729. var mesh = meshes[i];
  69730. if (!mesh.parent) {
  69731. // Exclude controller meshes from picking results
  69732. mesh.isPickable = false;
  69733. // Handle root node, attach to the new parentMesh
  69734. childMesh = mesh;
  69735. break;
  69736. }
  69737. }
  69738. if (childMesh) {
  69739. childMesh.setParent(parentMesh);
  69740. // Create our mesh info. Note that this method will always return non-null.
  69741. loadedMeshInfo = this.createMeshInfo(parentMesh);
  69742. }
  69743. else {
  69744. BABYLON.Tools.Warn('Could not find root node in model file.');
  69745. }
  69746. return loadedMeshInfo;
  69747. };
  69748. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  69749. var loadedMeshInfo = new LoadedMeshInfo();
  69750. var i;
  69751. loadedMeshInfo.rootNode = rootNode;
  69752. // Reset the caches
  69753. loadedMeshInfo.buttonMeshes = {};
  69754. loadedMeshInfo.axisMeshes = {};
  69755. // Button Meshes
  69756. for (i = 0; i < this._mapping.buttons.length; i++) {
  69757. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  69758. if (!buttonMeshName) {
  69759. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  69760. continue;
  69761. }
  69762. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  69763. if (!buttonMesh) {
  69764. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  69765. continue;
  69766. }
  69767. var buttonMeshInfo = {
  69768. index: i,
  69769. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  69770. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  69771. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  69772. };
  69773. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  69774. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  69775. }
  69776. else {
  69777. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  69778. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  69779. '(VALUE: ' + !!buttonMeshInfo.value +
  69780. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  69781. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  69782. ')');
  69783. }
  69784. }
  69785. // Axis Meshes
  69786. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  69787. var axisMeshName = this._mapping.axisMeshNames[i];
  69788. if (!axisMeshName) {
  69789. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  69790. continue;
  69791. }
  69792. var axisMesh = getChildByName(rootNode, axisMeshName);
  69793. if (!axisMesh) {
  69794. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  69795. continue;
  69796. }
  69797. var axisMeshInfo = {
  69798. index: i,
  69799. value: getImmediateChildByName(axisMesh, 'VALUE'),
  69800. min: getImmediateChildByName(axisMesh, 'MIN'),
  69801. max: getImmediateChildByName(axisMesh, 'MAX')
  69802. };
  69803. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  69804. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  69805. }
  69806. else {
  69807. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  69808. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  69809. '(VALUE: ' + !!axisMeshInfo.value +
  69810. ', MIN: ' + !!axisMeshInfo.min +
  69811. ', MAX:' + !!axisMeshInfo.max +
  69812. ')');
  69813. }
  69814. }
  69815. // Pointing Ray
  69816. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  69817. if (!loadedMeshInfo.pointingPoseNode) {
  69818. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  69819. }
  69820. return loadedMeshInfo;
  69821. // Look through all children recursively. This will return null if no mesh exists with the given name.
  69822. function getChildByName(node, name) {
  69823. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  69824. }
  69825. // Look through only immediate children. This will return null if no mesh exists with the given name.
  69826. function getImmediateChildByName(node, name) {
  69827. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  69828. }
  69829. };
  69830. /**
  69831. * Gets the ray of the controller in the direction the controller is pointing
  69832. * @param length the length the resulting ray should be
  69833. * @returns a ray in the direction the controller is pointing
  69834. */
  69835. WindowsMotionController.prototype.getForwardRay = function (length) {
  69836. if (length === void 0) { length = 100; }
  69837. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  69838. return _super.prototype.getForwardRay.call(this, length);
  69839. }
  69840. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  69841. var origin = m.getTranslation();
  69842. var forward = new BABYLON.Vector3(0, 0, -1);
  69843. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  69844. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  69845. return new BABYLON.Ray(origin, direction, length);
  69846. };
  69847. /**
  69848. * Disposes of the controller
  69849. */
  69850. WindowsMotionController.prototype.dispose = function () {
  69851. _super.prototype.dispose.call(this);
  69852. this.onTrackpadChangedObservable.clear();
  69853. };
  69854. /**
  69855. * The base url used to load the left and right controller models
  69856. */
  69857. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  69858. /**
  69859. * The name of the left controller model file
  69860. */
  69861. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  69862. /**
  69863. * The name of the right controller model file
  69864. */
  69865. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  69866. /**
  69867. * The controller name prefix for this controller type
  69868. */
  69869. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  69870. /**
  69871. * The controller id pattern for this controller type
  69872. */
  69873. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  69874. return WindowsMotionController;
  69875. }(BABYLON.WebVRController));
  69876. BABYLON.WindowsMotionController = WindowsMotionController;
  69877. })(BABYLON || (BABYLON = {}));
  69878. //# sourceMappingURL=babylon.windowsMotionController.js.map
  69879. "use strict";
  69880. var BABYLON;
  69881. (function (BABYLON) {
  69882. /**
  69883. * Gear VR Controller
  69884. */
  69885. var GearVRController = /** @class */ (function (_super) {
  69886. __extends(GearVRController, _super);
  69887. /**
  69888. * Creates a new GearVRController from a gamepad
  69889. * @param vrGamepad the gamepad that the controller should be created from
  69890. */
  69891. function GearVRController(vrGamepad) {
  69892. var _this = _super.call(this, vrGamepad) || this;
  69893. _this._buttonIndexToObservableNameMap = [
  69894. 'onTrackpadChangedObservable',
  69895. 'onTriggerStateChangedObservable' // Trigger
  69896. ];
  69897. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  69898. return _this;
  69899. }
  69900. /**
  69901. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  69902. * @param scene scene in which to add meshes
  69903. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  69904. */
  69905. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  69906. var _this = this;
  69907. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  69908. _this._defaultModel = newMeshes[1];
  69909. _this.attachToMesh(_this._defaultModel);
  69910. if (meshLoaded) {
  69911. meshLoaded(_this._defaultModel);
  69912. }
  69913. });
  69914. };
  69915. /**
  69916. * Called once for each button that changed state since the last frame
  69917. * @param buttonIdx Which button index changed
  69918. * @param state New state of the button
  69919. * @param changes Which properties on the state changed since last frame
  69920. */
  69921. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  69922. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  69923. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  69924. // Only emit events for buttons that we know how to map from index to observable
  69925. var observable = this[observableName];
  69926. if (observable) {
  69927. observable.notifyObservers(state);
  69928. }
  69929. }
  69930. };
  69931. /**
  69932. * Base Url for the controller model.
  69933. */
  69934. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  69935. /**
  69936. * File name for the controller model.
  69937. */
  69938. GearVRController.MODEL_FILENAME = 'generic.babylon';
  69939. /**
  69940. * Gamepad Id prefix used to identify this controller.
  69941. */
  69942. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  69943. return GearVRController;
  69944. }(BABYLON.WebVRController));
  69945. BABYLON.GearVRController = GearVRController;
  69946. })(BABYLON || (BABYLON = {}));
  69947. //# sourceMappingURL=babylon.gearVRController.js.map
  69948. "use strict";
  69949. var BABYLON;
  69950. (function (BABYLON) {
  69951. /**
  69952. * Google Daydream controller
  69953. */
  69954. var DaydreamController = /** @class */ (function (_super) {
  69955. __extends(DaydreamController, _super);
  69956. /**
  69957. * Creates a new DaydreamController from a gamepad
  69958. * @param vrGamepad the gamepad that the controller should be created from
  69959. */
  69960. function DaydreamController(vrGamepad) {
  69961. var _this = _super.call(this, vrGamepad) || this;
  69962. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  69963. return _this;
  69964. }
  69965. /**
  69966. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  69967. * @param scene scene in which to add meshes
  69968. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  69969. */
  69970. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  69971. var _this = this;
  69972. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  69973. _this._defaultModel = newMeshes[1];
  69974. _this.attachToMesh(_this._defaultModel);
  69975. if (meshLoaded) {
  69976. meshLoaded(_this._defaultModel);
  69977. }
  69978. });
  69979. };
  69980. /**
  69981. * Called once for each button that changed state since the last frame
  69982. * @param buttonIdx Which button index changed
  69983. * @param state New state of the button
  69984. * @param changes Which properties on the state changed since last frame
  69985. */
  69986. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  69987. // Daydream controller only has 1 GamepadButton (on the trackpad).
  69988. if (buttonIdx === 0) {
  69989. var observable = this.onTriggerStateChangedObservable;
  69990. if (observable) {
  69991. observable.notifyObservers(state);
  69992. }
  69993. }
  69994. else {
  69995. // If the app or home buttons are ever made available
  69996. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  69997. }
  69998. };
  69999. /**
  70000. * Base Url for the controller model.
  70001. */
  70002. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  70003. /**
  70004. * File name for the controller model.
  70005. */
  70006. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  70007. /**
  70008. * Gamepad Id prefix used to identify Daydream Controller.
  70009. */
  70010. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  70011. return DaydreamController;
  70012. }(BABYLON.WebVRController));
  70013. BABYLON.DaydreamController = DaydreamController;
  70014. })(BABYLON || (BABYLON = {}));
  70015. //# sourceMappingURL=babylon.daydreamController.js.map
  70016. "use strict";
  70017. var BABYLON;
  70018. (function (BABYLON) {
  70019. var FollowCamera = /** @class */ (function (_super) {
  70020. __extends(FollowCamera, _super);
  70021. function FollowCamera(name, position, scene, lockedTarget) {
  70022. if (lockedTarget === void 0) { lockedTarget = null; }
  70023. var _this = _super.call(this, name, position, scene) || this;
  70024. _this.radius = 12;
  70025. _this.rotationOffset = 0;
  70026. _this.heightOffset = 4;
  70027. _this.cameraAcceleration = 0.05;
  70028. _this.maxCameraSpeed = 20;
  70029. _this.lockedTarget = lockedTarget;
  70030. return _this;
  70031. }
  70032. FollowCamera.prototype.getRadians = function (degrees) {
  70033. return degrees * Math.PI / 180;
  70034. };
  70035. FollowCamera.prototype.follow = function (cameraTarget) {
  70036. if (!cameraTarget)
  70037. return;
  70038. var yRotation;
  70039. if (cameraTarget.rotationQuaternion) {
  70040. var rotMatrix = new BABYLON.Matrix();
  70041. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  70042. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  70043. }
  70044. else {
  70045. yRotation = cameraTarget.rotation.y;
  70046. }
  70047. var radians = this.getRadians(this.rotationOffset) + yRotation;
  70048. var targetPosition = cameraTarget.getAbsolutePosition();
  70049. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  70050. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  70051. var dx = targetX - this.position.x;
  70052. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  70053. var dz = (targetZ) - this.position.z;
  70054. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  70055. var vy = dy * this.cameraAcceleration;
  70056. var vz = dz * this.cameraAcceleration * 2;
  70057. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  70058. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  70059. }
  70060. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  70061. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  70062. }
  70063. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  70064. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  70065. }
  70066. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  70067. this.setTarget(targetPosition);
  70068. };
  70069. FollowCamera.prototype._checkInputs = function () {
  70070. _super.prototype._checkInputs.call(this);
  70071. if (this.lockedTarget) {
  70072. this.follow(this.lockedTarget);
  70073. }
  70074. };
  70075. FollowCamera.prototype.getClassName = function () {
  70076. return "FollowCamera";
  70077. };
  70078. __decorate([
  70079. BABYLON.serialize()
  70080. ], FollowCamera.prototype, "radius", void 0);
  70081. __decorate([
  70082. BABYLON.serialize()
  70083. ], FollowCamera.prototype, "rotationOffset", void 0);
  70084. __decorate([
  70085. BABYLON.serialize()
  70086. ], FollowCamera.prototype, "heightOffset", void 0);
  70087. __decorate([
  70088. BABYLON.serialize()
  70089. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  70090. __decorate([
  70091. BABYLON.serialize()
  70092. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  70093. __decorate([
  70094. BABYLON.serializeAsMeshReference("lockedTargetId")
  70095. ], FollowCamera.prototype, "lockedTarget", void 0);
  70096. return FollowCamera;
  70097. }(BABYLON.TargetCamera));
  70098. BABYLON.FollowCamera = FollowCamera;
  70099. var ArcFollowCamera = /** @class */ (function (_super) {
  70100. __extends(ArcFollowCamera, _super);
  70101. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  70102. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  70103. _this.alpha = alpha;
  70104. _this.beta = beta;
  70105. _this.radius = radius;
  70106. _this.target = target;
  70107. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  70108. _this.follow();
  70109. return _this;
  70110. }
  70111. ArcFollowCamera.prototype.follow = function () {
  70112. if (!this.target) {
  70113. return;
  70114. }
  70115. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  70116. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  70117. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  70118. var targetPosition = this.target.getAbsolutePosition();
  70119. this.position = targetPosition.add(this._cartesianCoordinates);
  70120. this.setTarget(targetPosition);
  70121. };
  70122. ArcFollowCamera.prototype._checkInputs = function () {
  70123. _super.prototype._checkInputs.call(this);
  70124. this.follow();
  70125. };
  70126. ArcFollowCamera.prototype.getClassName = function () {
  70127. return "ArcFollowCamera";
  70128. };
  70129. return ArcFollowCamera;
  70130. }(BABYLON.TargetCamera));
  70131. BABYLON.ArcFollowCamera = ArcFollowCamera;
  70132. })(BABYLON || (BABYLON = {}));
  70133. //# sourceMappingURL=babylon.followCamera.js.map
  70134. "use strict";
  70135. var BABYLON;
  70136. (function (BABYLON) {
  70137. // We're mainly based on the logic defined into the FreeCamera code
  70138. var UniversalCamera = /** @class */ (function (_super) {
  70139. __extends(UniversalCamera, _super);
  70140. //-- end properties for backward compatibility for inputs
  70141. function UniversalCamera(name, position, scene) {
  70142. var _this = _super.call(this, name, position, scene) || this;
  70143. _this.inputs.addGamepad();
  70144. return _this;
  70145. }
  70146. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  70147. //-- Begin properties for backward compatibility for inputs
  70148. get: function () {
  70149. var gamepad = this.inputs.attached["gamepad"];
  70150. if (gamepad)
  70151. return gamepad.gamepadAngularSensibility;
  70152. return 0;
  70153. },
  70154. set: function (value) {
  70155. var gamepad = this.inputs.attached["gamepad"];
  70156. if (gamepad)
  70157. gamepad.gamepadAngularSensibility = value;
  70158. },
  70159. enumerable: true,
  70160. configurable: true
  70161. });
  70162. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  70163. get: function () {
  70164. var gamepad = this.inputs.attached["gamepad"];
  70165. if (gamepad)
  70166. return gamepad.gamepadMoveSensibility;
  70167. return 0;
  70168. },
  70169. set: function (value) {
  70170. var gamepad = this.inputs.attached["gamepad"];
  70171. if (gamepad)
  70172. gamepad.gamepadMoveSensibility = value;
  70173. },
  70174. enumerable: true,
  70175. configurable: true
  70176. });
  70177. UniversalCamera.prototype.getClassName = function () {
  70178. return "UniversalCamera";
  70179. };
  70180. return UniversalCamera;
  70181. }(BABYLON.TouchCamera));
  70182. BABYLON.UniversalCamera = UniversalCamera;
  70183. })(BABYLON || (BABYLON = {}));
  70184. //# sourceMappingURL=babylon.universalCamera.js.map
  70185. "use strict";
  70186. var BABYLON;
  70187. (function (BABYLON) {
  70188. // We're mainly based on the logic defined into the FreeCamera code
  70189. var GamepadCamera = /** @class */ (function (_super) {
  70190. __extends(GamepadCamera, _super);
  70191. //-- end properties for backward compatibility for inputs
  70192. function GamepadCamera(name, position, scene) {
  70193. return _super.call(this, name, position, scene) || this;
  70194. }
  70195. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  70196. //-- Begin properties for backward compatibility for inputs
  70197. get: function () {
  70198. var gamepad = this.inputs.attached["gamepad"];
  70199. if (gamepad)
  70200. return gamepad.gamepadAngularSensibility;
  70201. return 0;
  70202. },
  70203. set: function (value) {
  70204. var gamepad = this.inputs.attached["gamepad"];
  70205. if (gamepad)
  70206. gamepad.gamepadAngularSensibility = value;
  70207. },
  70208. enumerable: true,
  70209. configurable: true
  70210. });
  70211. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  70212. get: function () {
  70213. var gamepad = this.inputs.attached["gamepad"];
  70214. if (gamepad)
  70215. return gamepad.gamepadMoveSensibility;
  70216. return 0;
  70217. },
  70218. set: function (value) {
  70219. var gamepad = this.inputs.attached["gamepad"];
  70220. if (gamepad)
  70221. gamepad.gamepadMoveSensibility = value;
  70222. },
  70223. enumerable: true,
  70224. configurable: true
  70225. });
  70226. GamepadCamera.prototype.getClassName = function () {
  70227. return "GamepadCamera";
  70228. };
  70229. return GamepadCamera;
  70230. }(BABYLON.UniversalCamera));
  70231. BABYLON.GamepadCamera = GamepadCamera;
  70232. })(BABYLON || (BABYLON = {}));
  70233. //# sourceMappingURL=babylon.gamepadCamera.js.map
  70234. "use strict";
  70235. var BABYLON;
  70236. (function (BABYLON) {
  70237. var PostProcessRenderPipelineManager = /** @class */ (function () {
  70238. function PostProcessRenderPipelineManager() {
  70239. this._renderPipelines = {};
  70240. }
  70241. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  70242. this._renderPipelines[renderPipeline._name] = renderPipeline;
  70243. };
  70244. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  70245. if (unique === void 0) { unique = false; }
  70246. var renderPipeline = this._renderPipelines[renderPipelineName];
  70247. if (!renderPipeline) {
  70248. return;
  70249. }
  70250. renderPipeline._attachCameras(cameras, unique);
  70251. };
  70252. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  70253. var renderPipeline = this._renderPipelines[renderPipelineName];
  70254. if (!renderPipeline) {
  70255. return;
  70256. }
  70257. renderPipeline._detachCameras(cameras);
  70258. };
  70259. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  70260. var renderPipeline = this._renderPipelines[renderPipelineName];
  70261. if (!renderPipeline) {
  70262. return;
  70263. }
  70264. renderPipeline._enableEffect(renderEffectName, cameras);
  70265. };
  70266. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  70267. var renderPipeline = this._renderPipelines[renderPipelineName];
  70268. if (!renderPipeline) {
  70269. return;
  70270. }
  70271. renderPipeline._disableEffect(renderEffectName, cameras);
  70272. };
  70273. PostProcessRenderPipelineManager.prototype.update = function () {
  70274. for (var renderPipelineName in this._renderPipelines) {
  70275. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  70276. var pipeline = this._renderPipelines[renderPipelineName];
  70277. if (!pipeline.isSupported) {
  70278. pipeline.dispose();
  70279. delete this._renderPipelines[renderPipelineName];
  70280. }
  70281. else {
  70282. pipeline._update();
  70283. }
  70284. }
  70285. }
  70286. };
  70287. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  70288. for (var renderPipelineName in this._renderPipelines) {
  70289. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  70290. var pipeline = this._renderPipelines[renderPipelineName];
  70291. pipeline._rebuild();
  70292. }
  70293. }
  70294. };
  70295. PostProcessRenderPipelineManager.prototype.dispose = function () {
  70296. for (var renderPipelineName in this._renderPipelines) {
  70297. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  70298. var pipeline = this._renderPipelines[renderPipelineName];
  70299. pipeline.dispose();
  70300. }
  70301. }
  70302. };
  70303. return PostProcessRenderPipelineManager;
  70304. }());
  70305. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  70306. })(BABYLON || (BABYLON = {}));
  70307. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  70308. "use strict";
  70309. var BABYLON;
  70310. (function (BABYLON) {
  70311. /**
  70312. * This represents a set of one or more post processes in Babylon.
  70313. * A post process can be used to apply a shader to a texture after it is rendered.
  70314. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  70315. */
  70316. var PostProcessRenderEffect = /** @class */ (function () {
  70317. /**
  70318. * Instantiates a post process render effect.
  70319. * A post process can be used to apply a shader to a texture after it is rendered.
  70320. * @param engine The engine the effect is tied to
  70321. * @param name The name of the effect
  70322. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  70323. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  70324. */
  70325. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  70326. this._name = name;
  70327. this._singleInstance = singleInstance || true;
  70328. this._getPostProcesses = getPostProcesses;
  70329. this._cameras = {};
  70330. this._indicesForCamera = {};
  70331. this._postProcesses = {};
  70332. }
  70333. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  70334. /**
  70335. * Checks if all the post processes in the effect are supported.
  70336. */
  70337. get: function () {
  70338. for (var index in this._postProcesses) {
  70339. for (var ppIndex in this._postProcesses[index]) {
  70340. if (!this._postProcesses[index][ppIndex].isSupported) {
  70341. return false;
  70342. }
  70343. }
  70344. }
  70345. return true;
  70346. },
  70347. enumerable: true,
  70348. configurable: true
  70349. });
  70350. /**
  70351. * Updates the current state of the effect
  70352. */
  70353. PostProcessRenderEffect.prototype._update = function () {
  70354. };
  70355. /**
  70356. * Attaches the effect on cameras
  70357. * @param cameras The camera to attach to.
  70358. */
  70359. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  70360. var _this = this;
  70361. var cameraKey;
  70362. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  70363. if (!cams) {
  70364. return;
  70365. }
  70366. for (var i = 0; i < cams.length; i++) {
  70367. var camera = cams[i];
  70368. var cameraName = camera.name;
  70369. if (this._singleInstance) {
  70370. cameraKey = 0;
  70371. }
  70372. else {
  70373. cameraKey = cameraName;
  70374. }
  70375. if (!this._postProcesses[cameraKey]) {
  70376. var postProcess = this._getPostProcesses();
  70377. if (postProcess) {
  70378. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  70379. }
  70380. }
  70381. if (!this._indicesForCamera[cameraName]) {
  70382. this._indicesForCamera[cameraName] = [];
  70383. }
  70384. this._postProcesses[cameraKey].forEach(function (postProcess) {
  70385. var index = camera.attachPostProcess(postProcess);
  70386. _this._indicesForCamera[cameraName].push(index);
  70387. });
  70388. if (!this._cameras[cameraName]) {
  70389. this._cameras[cameraName] = camera;
  70390. }
  70391. }
  70392. };
  70393. /**
  70394. * Detatches the effect on cameras
  70395. * @param cameras The camera to detatch from.
  70396. */
  70397. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  70398. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  70399. if (!cams) {
  70400. return;
  70401. }
  70402. for (var i = 0; i < cams.length; i++) {
  70403. var camera = cams[i];
  70404. var cameraName = camera.name;
  70405. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  70406. camera.detachPostProcess(postProcess);
  70407. });
  70408. if (this._cameras[cameraName]) {
  70409. //this._indicesForCamera.splice(index, 1);
  70410. this._cameras[cameraName] = null;
  70411. }
  70412. }
  70413. };
  70414. /**
  70415. * Enables the effect on given cameras
  70416. * @param cameras The camera to enable.
  70417. */
  70418. PostProcessRenderEffect.prototype._enable = function (cameras) {
  70419. var _this = this;
  70420. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  70421. if (!cams) {
  70422. return;
  70423. }
  70424. for (var i = 0; i < cams.length; i++) {
  70425. var camera = cams[i];
  70426. var cameraName = camera.name;
  70427. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  70428. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  70429. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  70430. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  70431. });
  70432. }
  70433. }
  70434. }
  70435. };
  70436. /**
  70437. * Disables the effect on the given cameras
  70438. * @param cameras The camera to disable.
  70439. */
  70440. PostProcessRenderEffect.prototype._disable = function (cameras) {
  70441. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  70442. if (!cams) {
  70443. return;
  70444. }
  70445. for (var i = 0; i < cams.length; i++) {
  70446. var camera = cams[i];
  70447. var cameraName = camera.name;
  70448. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  70449. camera.detachPostProcess(postProcess);
  70450. });
  70451. }
  70452. };
  70453. /**
  70454. * Gets a list of the post processes contained in the effect.
  70455. * @param camera The camera to get the post processes on.
  70456. * @returns The list of the post processes in the effect.
  70457. */
  70458. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  70459. if (this._singleInstance) {
  70460. return this._postProcesses[0];
  70461. }
  70462. else {
  70463. if (!camera) {
  70464. return null;
  70465. }
  70466. return this._postProcesses[camera.name];
  70467. }
  70468. };
  70469. return PostProcessRenderEffect;
  70470. }());
  70471. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  70472. })(BABYLON || (BABYLON = {}));
  70473. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  70474. "use strict";
  70475. var BABYLON;
  70476. (function (BABYLON) {
  70477. var PostProcessRenderPipeline = /** @class */ (function () {
  70478. function PostProcessRenderPipeline(engine, name) {
  70479. this.engine = engine;
  70480. this._name = name;
  70481. this._renderEffects = {};
  70482. this._renderEffectsForIsolatedPass = new Array();
  70483. this._cameras = [];
  70484. }
  70485. PostProcessRenderPipeline.prototype.getClassName = function () {
  70486. return "PostProcessRenderPipeline";
  70487. };
  70488. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  70489. get: function () {
  70490. for (var renderEffectName in this._renderEffects) {
  70491. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  70492. if (!this._renderEffects[renderEffectName].isSupported) {
  70493. return false;
  70494. }
  70495. }
  70496. }
  70497. return true;
  70498. },
  70499. enumerable: true,
  70500. configurable: true
  70501. });
  70502. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  70503. this._renderEffects[renderEffect._name] = renderEffect;
  70504. };
  70505. // private
  70506. PostProcessRenderPipeline.prototype._rebuild = function () {
  70507. };
  70508. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  70509. var renderEffects = this._renderEffects[renderEffectName];
  70510. if (!renderEffects) {
  70511. return;
  70512. }
  70513. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  70514. };
  70515. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  70516. var renderEffects = this._renderEffects[renderEffectName];
  70517. if (!renderEffects) {
  70518. return;
  70519. }
  70520. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  70521. };
  70522. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  70523. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  70524. if (!cams) {
  70525. return;
  70526. }
  70527. var indicesToDelete = [];
  70528. var i;
  70529. for (i = 0; i < cams.length; i++) {
  70530. var camera = cams[i];
  70531. var cameraName = camera.name;
  70532. if (this._cameras.indexOf(camera) === -1) {
  70533. this._cameras[cameraName] = camera;
  70534. }
  70535. else if (unique) {
  70536. indicesToDelete.push(i);
  70537. }
  70538. }
  70539. for (i = 0; i < indicesToDelete.length; i++) {
  70540. cameras.splice(indicesToDelete[i], 1);
  70541. }
  70542. for (var renderEffectName in this._renderEffects) {
  70543. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  70544. this._renderEffects[renderEffectName]._attachCameras(cams);
  70545. }
  70546. }
  70547. };
  70548. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  70549. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  70550. if (!cams) {
  70551. return;
  70552. }
  70553. for (var renderEffectName in this._renderEffects) {
  70554. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  70555. this._renderEffects[renderEffectName]._detachCameras(cams);
  70556. }
  70557. }
  70558. for (var i = 0; i < cams.length; i++) {
  70559. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  70560. }
  70561. };
  70562. PostProcessRenderPipeline.prototype._update = function () {
  70563. for (var renderEffectName in this._renderEffects) {
  70564. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  70565. this._renderEffects[renderEffectName]._update();
  70566. }
  70567. }
  70568. for (var i = 0; i < this._cameras.length; i++) {
  70569. var cameraName = this._cameras[i].name;
  70570. if (this._renderEffectsForIsolatedPass[cameraName]) {
  70571. this._renderEffectsForIsolatedPass[cameraName]._update();
  70572. }
  70573. }
  70574. };
  70575. PostProcessRenderPipeline.prototype._reset = function () {
  70576. this._renderEffects = {};
  70577. this._renderEffectsForIsolatedPass = new Array();
  70578. };
  70579. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  70580. // 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)
  70581. var effectKeys = Object.keys(this._renderEffects);
  70582. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  70583. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  70584. if (postProcesses) {
  70585. postProcesses[0].samples = sampleCount;
  70586. return true;
  70587. }
  70588. }
  70589. return false;
  70590. };
  70591. PostProcessRenderPipeline.prototype.dispose = function () {
  70592. // Must be implemented by children
  70593. };
  70594. __decorate([
  70595. BABYLON.serialize()
  70596. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  70597. return PostProcessRenderPipeline;
  70598. }());
  70599. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  70600. })(BABYLON || (BABYLON = {}));
  70601. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  70602. "use strict";
  70603. var BABYLON;
  70604. (function (BABYLON) {
  70605. /**
  70606. * This represents a depth renderer in Babylon.
  70607. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  70608. */
  70609. var DepthRenderer = /** @class */ (function () {
  70610. /**
  70611. * Instantiates a depth renderer
  70612. * @param scene The scene the renderer belongs to
  70613. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  70614. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  70615. */
  70616. function DepthRenderer(scene, type, camera) {
  70617. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  70618. if (camera === void 0) { camera = null; }
  70619. var _this = this;
  70620. this._scene = scene;
  70621. this._camera = camera;
  70622. var engine = scene.getEngine();
  70623. // Render target
  70624. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  70625. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70626. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70627. this._depthMap.refreshRate = 1;
  70628. this._depthMap.renderParticles = false;
  70629. this._depthMap.renderList = null;
  70630. // Camera to get depth map from to support multiple concurrent cameras
  70631. this._depthMap.activeCamera = this._camera;
  70632. this._depthMap.ignoreCameraViewport = true;
  70633. this._depthMap.useCameraPostProcesses = false;
  70634. // set default depth value to 1.0 (far away)
  70635. this._depthMap.onClearObservable.add(function (engine) {
  70636. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  70637. });
  70638. // Custom render function
  70639. var renderSubMesh = function (subMesh) {
  70640. var mesh = subMesh.getRenderingMesh();
  70641. var scene = _this._scene;
  70642. var engine = scene.getEngine();
  70643. var material = subMesh.getMaterial();
  70644. if (!material) {
  70645. return;
  70646. }
  70647. // Culling and reverse (right handed system)
  70648. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  70649. // Managing instances
  70650. var batch = mesh._getInstancesRenderList(subMesh._id);
  70651. if (batch.mustReturn) {
  70652. return;
  70653. }
  70654. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  70655. var camera = _this._camera || scene.activeCamera;
  70656. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  70657. engine.enableEffect(_this._effect);
  70658. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  70659. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  70660. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  70661. // Alpha test
  70662. if (material && material.needAlphaTesting()) {
  70663. var alphaTexture = material.getAlphaTestTexture();
  70664. if (alphaTexture) {
  70665. _this._effect.setTexture("diffuseSampler", alphaTexture);
  70666. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  70667. }
  70668. }
  70669. // Bones
  70670. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  70671. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  70672. }
  70673. // Draw
  70674. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  70675. }
  70676. };
  70677. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  70678. var index;
  70679. if (depthOnlySubMeshes.length) {
  70680. engine.setColorWrite(false);
  70681. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  70682. renderSubMesh(depthOnlySubMeshes.data[index]);
  70683. }
  70684. engine.setColorWrite(true);
  70685. }
  70686. for (index = 0; index < opaqueSubMeshes.length; index++) {
  70687. renderSubMesh(opaqueSubMeshes.data[index]);
  70688. }
  70689. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  70690. renderSubMesh(alphaTestSubMeshes.data[index]);
  70691. }
  70692. };
  70693. }
  70694. /**
  70695. * Creates the depth rendering effect and checks if the effect is ready.
  70696. * @param subMesh The submesh to be used to render the depth map of
  70697. * @param useInstances If multiple world instances should be used
  70698. * @returns if the depth renderer is ready to render the depth map
  70699. */
  70700. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  70701. var material = subMesh.getMaterial();
  70702. if (material.disableDepthWrite) {
  70703. return false;
  70704. }
  70705. var defines = [];
  70706. var attribs = [BABYLON.VertexBuffer.PositionKind];
  70707. var mesh = subMesh.getMesh();
  70708. // Alpha test
  70709. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  70710. defines.push("#define ALPHATEST");
  70711. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  70712. attribs.push(BABYLON.VertexBuffer.UVKind);
  70713. defines.push("#define UV1");
  70714. }
  70715. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  70716. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  70717. defines.push("#define UV2");
  70718. }
  70719. }
  70720. // Bones
  70721. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  70722. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  70723. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  70724. if (mesh.numBoneInfluencers > 4) {
  70725. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  70726. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  70727. }
  70728. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  70729. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  70730. }
  70731. else {
  70732. defines.push("#define NUM_BONE_INFLUENCERS 0");
  70733. }
  70734. // Instances
  70735. if (useInstances) {
  70736. defines.push("#define INSTANCES");
  70737. attribs.push("world0");
  70738. attribs.push("world1");
  70739. attribs.push("world2");
  70740. attribs.push("world3");
  70741. }
  70742. // Get correct effect
  70743. var join = defines.join("\n");
  70744. if (this._cachedDefines !== join) {
  70745. this._cachedDefines = join;
  70746. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  70747. }
  70748. return this._effect.isReady();
  70749. };
  70750. /**
  70751. * Gets the texture which the depth map will be written to.
  70752. * @returns The depth map texture
  70753. */
  70754. DepthRenderer.prototype.getDepthMap = function () {
  70755. return this._depthMap;
  70756. };
  70757. /**
  70758. * Disposes of the depth renderer.
  70759. */
  70760. DepthRenderer.prototype.dispose = function () {
  70761. this._depthMap.dispose();
  70762. };
  70763. return DepthRenderer;
  70764. }());
  70765. BABYLON.DepthRenderer = DepthRenderer;
  70766. })(BABYLON || (BABYLON = {}));
  70767. //# sourceMappingURL=babylon.depthRenderer.js.map
  70768. "use strict";
  70769. var BABYLON;
  70770. (function (BABYLON) {
  70771. var SSAORenderingPipeline = /** @class */ (function (_super) {
  70772. __extends(SSAORenderingPipeline, _super);
  70773. /**
  70774. * @constructor
  70775. * @param {string} name - The rendering pipeline name
  70776. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  70777. * @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 }
  70778. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  70779. */
  70780. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  70781. var _this = _super.call(this, scene.getEngine(), name) || this;
  70782. // Members
  70783. /**
  70784. * The PassPostProcess id in the pipeline that contains the original scene color
  70785. */
  70786. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  70787. /**
  70788. * The SSAO PostProcess id in the pipeline
  70789. */
  70790. _this.SSAORenderEffect = "SSAORenderEffect";
  70791. /**
  70792. * The horizontal blur PostProcess id in the pipeline
  70793. */
  70794. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  70795. /**
  70796. * The vertical blur PostProcess id in the pipeline
  70797. */
  70798. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  70799. /**
  70800. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  70801. */
  70802. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  70803. /**
  70804. * The output strength of the SSAO post-process. Default value is 1.0.
  70805. */
  70806. _this.totalStrength = 1.0;
  70807. /**
  70808. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  70809. */
  70810. _this.radius = 0.0001;
  70811. /**
  70812. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  70813. * Must not be equal to fallOff and superior to fallOff.
  70814. * Default value is 0.975
  70815. */
  70816. _this.area = 0.0075;
  70817. /**
  70818. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  70819. * Must not be equal to area and inferior to area.
  70820. * Default value is 0.0
  70821. */
  70822. _this.fallOff = 0.000001;
  70823. /**
  70824. * The base color of the SSAO post-process
  70825. * The final result is "base + ssao" between [0, 1]
  70826. */
  70827. _this.base = 0.5;
  70828. _this._firstUpdate = true;
  70829. _this._scene = scene;
  70830. // Set up assets
  70831. _this._createRandomTexture();
  70832. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  70833. var ssaoRatio = ratio.ssaoRatio || ratio;
  70834. var combineRatio = ratio.combineRatio || ratio;
  70835. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  70836. _this._createSSAOPostProcess(ssaoRatio);
  70837. _this._createBlurPostProcess(ssaoRatio);
  70838. _this._createSSAOCombinePostProcess(combineRatio);
  70839. // Set up pipeline
  70840. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  70841. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  70842. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  70843. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  70844. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  70845. // Finish
  70846. scene.postProcessRenderPipelineManager.addPipeline(_this);
  70847. if (cameras)
  70848. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  70849. return _this;
  70850. }
  70851. // Public Methods
  70852. /**
  70853. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  70854. */
  70855. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  70856. if (disableDepthRender === void 0) { disableDepthRender = false; }
  70857. for (var i = 0; i < this._scene.cameras.length; i++) {
  70858. var camera = this._scene.cameras[i];
  70859. this._originalColorPostProcess.dispose(camera);
  70860. this._ssaoPostProcess.dispose(camera);
  70861. this._blurHPostProcess.dispose(camera);
  70862. this._blurVPostProcess.dispose(camera);
  70863. this._ssaoCombinePostProcess.dispose(camera);
  70864. }
  70865. this._randomTexture.dispose();
  70866. if (disableDepthRender)
  70867. this._scene.disableDepthRenderer();
  70868. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  70869. _super.prototype.dispose.call(this);
  70870. };
  70871. // Private Methods
  70872. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  70873. var _this = this;
  70874. var size = 16;
  70875. 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);
  70876. 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);
  70877. this._blurHPostProcess.onActivateObservable.add(function () {
  70878. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  70879. _this._blurHPostProcess.kernel = size * dw;
  70880. });
  70881. this._blurVPostProcess.onActivateObservable.add(function () {
  70882. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  70883. _this._blurVPostProcess.kernel = size * dw;
  70884. });
  70885. };
  70886. SSAORenderingPipeline.prototype._rebuild = function () {
  70887. this._firstUpdate = true;
  70888. _super.prototype._rebuild.call(this);
  70889. };
  70890. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  70891. var _this = this;
  70892. var numSamples = 16;
  70893. var sampleSphere = [
  70894. 0.5381, 0.1856, -0.4319,
  70895. 0.1379, 0.2486, 0.4430,
  70896. 0.3371, 0.5679, -0.0057,
  70897. -0.6999, -0.0451, -0.0019,
  70898. 0.0689, -0.1598, -0.8547,
  70899. 0.0560, 0.0069, -0.1843,
  70900. -0.0146, 0.1402, 0.0762,
  70901. 0.0100, -0.1924, -0.0344,
  70902. -0.3577, -0.5301, -0.4358,
  70903. -0.3169, 0.1063, 0.0158,
  70904. 0.0103, -0.5869, 0.0046,
  70905. -0.0897, -0.4940, 0.3287,
  70906. 0.7119, -0.0154, -0.0918,
  70907. -0.0533, 0.0596, -0.5411,
  70908. 0.0352, -0.0631, 0.5460,
  70909. -0.4776, 0.2847, -0.0271
  70910. ];
  70911. var samplesFactor = 1.0 / numSamples;
  70912. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  70913. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  70914. "area", "fallOff", "base", "range", "viewport"
  70915. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  70916. this._ssaoPostProcess.onApply = function (effect) {
  70917. if (_this._firstUpdate) {
  70918. effect.setArray3("sampleSphere", sampleSphere);
  70919. effect.setFloat("samplesFactor", samplesFactor);
  70920. effect.setFloat("randTextureTiles", 4.0);
  70921. }
  70922. effect.setFloat("totalStrength", _this.totalStrength);
  70923. effect.setFloat("radius", _this.radius);
  70924. effect.setFloat("area", _this.area);
  70925. effect.setFloat("fallOff", _this.fallOff);
  70926. effect.setFloat("base", _this.base);
  70927. effect.setTexture("textureSampler", _this._depthTexture);
  70928. effect.setTexture("randomSampler", _this._randomTexture);
  70929. };
  70930. };
  70931. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  70932. var _this = this;
  70933. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  70934. this._ssaoCombinePostProcess.onApply = function (effect) {
  70935. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  70936. };
  70937. };
  70938. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  70939. var size = 512;
  70940. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  70941. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  70942. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  70943. var context = this._randomTexture.getContext();
  70944. var rand = function (min, max) {
  70945. return Math.random() * (max - min) + min;
  70946. };
  70947. var randVector = BABYLON.Vector3.Zero();
  70948. for (var x = 0; x < size; x++) {
  70949. for (var y = 0; y < size; y++) {
  70950. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  70951. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  70952. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  70953. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  70954. context.fillRect(x, y, 1, 1);
  70955. }
  70956. }
  70957. this._randomTexture.update(false);
  70958. };
  70959. __decorate([
  70960. BABYLON.serialize()
  70961. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  70962. __decorate([
  70963. BABYLON.serialize()
  70964. ], SSAORenderingPipeline.prototype, "radius", void 0);
  70965. __decorate([
  70966. BABYLON.serialize()
  70967. ], SSAORenderingPipeline.prototype, "area", void 0);
  70968. __decorate([
  70969. BABYLON.serialize()
  70970. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  70971. __decorate([
  70972. BABYLON.serialize()
  70973. ], SSAORenderingPipeline.prototype, "base", void 0);
  70974. return SSAORenderingPipeline;
  70975. }(BABYLON.PostProcessRenderPipeline));
  70976. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  70977. })(BABYLON || (BABYLON = {}));
  70978. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  70979. "use strict";
  70980. var BABYLON;
  70981. (function (BABYLON) {
  70982. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  70983. __extends(SSAO2RenderingPipeline, _super);
  70984. /**
  70985. * @constructor
  70986. * @param {string} name - The rendering pipeline name
  70987. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  70988. * @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 }
  70989. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  70990. */
  70991. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  70992. var _this = _super.call(this, scene.getEngine(), name) || this;
  70993. // Members
  70994. /**
  70995. * The PassPostProcess id in the pipeline that contains the original scene color
  70996. */
  70997. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  70998. /**
  70999. * The SSAO PostProcess id in the pipeline
  71000. */
  71001. _this.SSAORenderEffect = "SSAORenderEffect";
  71002. /**
  71003. * The horizontal blur PostProcess id in the pipeline
  71004. */
  71005. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  71006. /**
  71007. * The vertical blur PostProcess id in the pipeline
  71008. */
  71009. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  71010. /**
  71011. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  71012. */
  71013. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  71014. /**
  71015. * The output strength of the SSAO post-process. Default value is 1.0.
  71016. */
  71017. _this.totalStrength = 1.0;
  71018. /**
  71019. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  71020. */
  71021. _this.maxZ = 100.0;
  71022. /**
  71023. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  71024. */
  71025. _this.minZAspect = 0.2;
  71026. /**
  71027. * Number of samples used for the SSAO calculations. Default value is 8
  71028. */
  71029. _this._samples = 8;
  71030. /**
  71031. * Are we using bilateral blur ?
  71032. */
  71033. _this._expensiveBlur = true;
  71034. /**
  71035. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  71036. */
  71037. _this.radius = 2.0;
  71038. /**
  71039. * The base color of the SSAO post-process
  71040. * The final result is "base + ssao" between [0, 1]
  71041. */
  71042. _this.base = 0.1;
  71043. _this._firstUpdate = true;
  71044. _this._scene = scene;
  71045. if (!_this.isSupported) {
  71046. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  71047. return _this;
  71048. }
  71049. var ssaoRatio = ratio.ssaoRatio || ratio;
  71050. var blurRatio = ratio.blurRatio || ratio;
  71051. // Set up assets
  71052. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  71053. _this._createRandomTexture();
  71054. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  71055. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  71056. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  71057. _this._createSSAOPostProcess(1.0);
  71058. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  71059. _this._createSSAOCombinePostProcess(blurRatio);
  71060. // Set up pipeline
  71061. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  71062. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  71063. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  71064. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  71065. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  71066. // Finish
  71067. scene.postProcessRenderPipelineManager.addPipeline(_this);
  71068. if (cameras)
  71069. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  71070. return _this;
  71071. }
  71072. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  71073. get: function () {
  71074. return this._samples;
  71075. },
  71076. set: function (n) {
  71077. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  71078. this._samples = n;
  71079. this._sampleSphere = this._generateHemisphere();
  71080. this._firstUpdate = true;
  71081. },
  71082. enumerable: true,
  71083. configurable: true
  71084. });
  71085. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  71086. get: function () {
  71087. return this._expensiveBlur;
  71088. },
  71089. set: function (b) {
  71090. 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"]);
  71091. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  71092. this._expensiveBlur = b;
  71093. this._firstUpdate = true;
  71094. },
  71095. enumerable: true,
  71096. configurable: true
  71097. });
  71098. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  71099. /**
  71100. * Support test.
  71101. */
  71102. get: function () {
  71103. var engine = BABYLON.Engine.LastCreatedEngine;
  71104. if (!engine) {
  71105. return false;
  71106. }
  71107. return engine.getCaps().drawBuffersExtension;
  71108. },
  71109. enumerable: true,
  71110. configurable: true
  71111. });
  71112. // Public Methods
  71113. /**
  71114. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  71115. */
  71116. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  71117. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  71118. for (var i = 0; i < this._scene.cameras.length; i++) {
  71119. var camera = this._scene.cameras[i];
  71120. this._originalColorPostProcess.dispose(camera);
  71121. this._ssaoPostProcess.dispose(camera);
  71122. this._blurHPostProcess.dispose(camera);
  71123. this._blurVPostProcess.dispose(camera);
  71124. this._ssaoCombinePostProcess.dispose(camera);
  71125. }
  71126. this._randomTexture.dispose();
  71127. if (disableGeometryBufferRenderer)
  71128. this._scene.disableGeometryBufferRenderer();
  71129. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  71130. _super.prototype.dispose.call(this);
  71131. };
  71132. // Private Methods
  71133. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  71134. var _this = this;
  71135. this._samplerOffsets = [];
  71136. var expensive = this.expensiveBlur;
  71137. for (var i = -8; i < 8; i++) {
  71138. this._samplerOffsets.push(i * 2 + 0.5);
  71139. }
  71140. 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");
  71141. this._blurHPostProcess.onApply = function (effect) {
  71142. if (!_this._scene.activeCamera) {
  71143. return;
  71144. }
  71145. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  71146. effect.setFloat("near", _this._scene.activeCamera.minZ);
  71147. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  71148. effect.setFloat("radius", _this.radius);
  71149. effect.setTexture("depthSampler", _this._depthTexture);
  71150. if (_this._firstUpdate) {
  71151. effect.setArray("samplerOffsets", _this._samplerOffsets);
  71152. }
  71153. };
  71154. 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");
  71155. this._blurVPostProcess.onApply = function (effect) {
  71156. if (!_this._scene.activeCamera) {
  71157. return;
  71158. }
  71159. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  71160. effect.setFloat("near", _this._scene.activeCamera.minZ);
  71161. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  71162. effect.setFloat("radius", _this.radius);
  71163. effect.setTexture("depthSampler", _this._depthTexture);
  71164. if (_this._firstUpdate) {
  71165. effect.setArray("samplerOffsets", _this._samplerOffsets);
  71166. _this._firstUpdate = false;
  71167. }
  71168. };
  71169. };
  71170. SSAO2RenderingPipeline.prototype._rebuild = function () {
  71171. this._firstUpdate = true;
  71172. _super.prototype._rebuild.call(this);
  71173. };
  71174. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  71175. var numSamples = this.samples;
  71176. var result = [];
  71177. var vector, scale;
  71178. var rand = function (min, max) {
  71179. return Math.random() * (max - min) + min;
  71180. };
  71181. var i = 0;
  71182. while (i < numSamples) {
  71183. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  71184. vector.normalize();
  71185. scale = i / numSamples;
  71186. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  71187. vector.scaleInPlace(scale);
  71188. result.push(vector.x, vector.y, vector.z);
  71189. i++;
  71190. }
  71191. return result;
  71192. };
  71193. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  71194. var _this = this;
  71195. var numSamples = this.samples;
  71196. this._sampleSphere = this._generateHemisphere();
  71197. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  71198. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  71199. "base", "range", "projection", "near", "far", "texelSize",
  71200. "xViewport", "yViewport", "maxZ", "minZAspect"
  71201. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  71202. this._ssaoPostProcess.onApply = function (effect) {
  71203. if (_this._firstUpdate) {
  71204. effect.setArray3("sampleSphere", _this._sampleSphere);
  71205. effect.setFloat("randTextureTiles", 4.0);
  71206. }
  71207. if (!_this._scene.activeCamera) {
  71208. return;
  71209. }
  71210. effect.setFloat("samplesFactor", 1 / _this.samples);
  71211. effect.setFloat("totalStrength", _this.totalStrength);
  71212. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  71213. effect.setFloat("radius", _this.radius);
  71214. effect.setFloat("maxZ", _this.maxZ);
  71215. effect.setFloat("minZAspect", _this.minZAspect);
  71216. effect.setFloat("base", _this.base);
  71217. effect.setFloat("near", _this._scene.activeCamera.minZ);
  71218. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  71219. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  71220. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  71221. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  71222. effect.setTexture("textureSampler", _this._depthTexture);
  71223. effect.setTexture("normalSampler", _this._normalTexture);
  71224. effect.setTexture("randomSampler", _this._randomTexture);
  71225. };
  71226. };
  71227. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  71228. var _this = this;
  71229. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  71230. this._ssaoCombinePostProcess.onApply = function (effect) {
  71231. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  71232. };
  71233. };
  71234. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  71235. var size = 512;
  71236. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  71237. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  71238. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  71239. var context = this._randomTexture.getContext();
  71240. var rand = function (min, max) {
  71241. return Math.random() * (max - min) + min;
  71242. };
  71243. var randVector = BABYLON.Vector3.Zero();
  71244. for (var x = 0; x < size; x++) {
  71245. for (var y = 0; y < size; y++) {
  71246. randVector.x = rand(0.0, 1.0);
  71247. randVector.y = rand(0.0, 1.0);
  71248. randVector.z = 0.0;
  71249. randVector.normalize();
  71250. randVector.scaleInPlace(255);
  71251. randVector.x = Math.floor(randVector.x);
  71252. randVector.y = Math.floor(randVector.y);
  71253. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  71254. context.fillRect(x, y, 1, 1);
  71255. }
  71256. }
  71257. this._randomTexture.update(false);
  71258. };
  71259. __decorate([
  71260. BABYLON.serialize()
  71261. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  71262. __decorate([
  71263. BABYLON.serialize()
  71264. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  71265. __decorate([
  71266. BABYLON.serialize()
  71267. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  71268. __decorate([
  71269. BABYLON.serialize("samples")
  71270. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  71271. __decorate([
  71272. BABYLON.serialize("expensiveBlur")
  71273. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  71274. __decorate([
  71275. BABYLON.serialize()
  71276. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  71277. __decorate([
  71278. BABYLON.serialize()
  71279. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  71280. return SSAO2RenderingPipeline;
  71281. }(BABYLON.PostProcessRenderPipeline));
  71282. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  71283. })(BABYLON || (BABYLON = {}));
  71284. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  71285. "use strict";
  71286. // BABYLON.JS Chromatic Aberration GLSL Shader
  71287. // Author: Olivier Guyot
  71288. // Separates very slightly R, G and B colors on the edges of the screen
  71289. // Inspired by Francois Tarlier & Martins Upitis
  71290. var BABYLON;
  71291. (function (BABYLON) {
  71292. var LensRenderingPipeline = /** @class */ (function (_super) {
  71293. __extends(LensRenderingPipeline, _super);
  71294. /**
  71295. * @constructor
  71296. *
  71297. * Effect parameters are as follow:
  71298. * {
  71299. * chromatic_aberration: number; // from 0 to x (1 for realism)
  71300. * edge_blur: number; // from 0 to x (1 for realism)
  71301. * distortion: number; // from 0 to x (1 for realism)
  71302. * grain_amount: number; // from 0 to 1
  71303. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  71304. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  71305. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  71306. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  71307. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  71308. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  71309. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  71310. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  71311. * }
  71312. * Note: if an effect parameter is unset, effect is disabled
  71313. *
  71314. * @param {string} name - The rendering pipeline name
  71315. * @param {object} parameters - An object containing all parameters (see above)
  71316. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  71317. * @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)
  71318. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  71319. */
  71320. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  71321. if (ratio === void 0) { ratio = 1.0; }
  71322. var _this = _super.call(this, scene.getEngine(), name) || this;
  71323. // Lens effects can be of the following:
  71324. // - chromatic aberration (slight shift of RGB colors)
  71325. // - blur on the edge of the lens
  71326. // - lens distortion
  71327. // - depth-of-field blur & highlights enhancing
  71328. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  71329. // - grain effect (noise or custom texture)
  71330. // Two additional texture samplers are needed:
  71331. // - depth map (for depth-of-field)
  71332. // - grain texture
  71333. /**
  71334. * The chromatic aberration PostProcess id in the pipeline
  71335. */
  71336. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  71337. /**
  71338. * The highlights enhancing PostProcess id in the pipeline
  71339. */
  71340. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  71341. /**
  71342. * The depth-of-field PostProcess id in the pipeline
  71343. */
  71344. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  71345. _this._scene = scene;
  71346. // Fetch texture samplers
  71347. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  71348. if (parameters.grain_texture) {
  71349. _this._grainTexture = parameters.grain_texture;
  71350. }
  71351. else {
  71352. _this._createGrainTexture();
  71353. }
  71354. // save parameters
  71355. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  71356. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  71357. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  71358. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  71359. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  71360. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  71361. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  71362. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  71363. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  71364. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  71365. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  71366. // Create effects
  71367. _this._createChromaticAberrationPostProcess(ratio);
  71368. _this._createHighlightsPostProcess(ratio);
  71369. _this._createDepthOfFieldPostProcess(ratio / 4);
  71370. // Set up pipeline
  71371. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  71372. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  71373. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  71374. if (_this._highlightsGain === -1) {
  71375. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  71376. }
  71377. // Finish
  71378. scene.postProcessRenderPipelineManager.addPipeline(_this);
  71379. if (cameras) {
  71380. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  71381. }
  71382. return _this;
  71383. }
  71384. // public methods (self explanatory)
  71385. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  71386. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  71387. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  71388. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  71389. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  71390. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  71391. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  71392. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  71393. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  71394. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  71395. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  71396. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  71397. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  71398. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  71399. };
  71400. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  71401. this._highlightsPostProcess.updateEffect();
  71402. };
  71403. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  71404. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  71405. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  71406. this._highlightsGain = amount;
  71407. };
  71408. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  71409. if (this._highlightsGain === -1) {
  71410. this._highlightsGain = 1.0;
  71411. }
  71412. this._highlightsThreshold = amount;
  71413. };
  71414. LensRenderingPipeline.prototype.disableHighlights = function () {
  71415. this._highlightsGain = -1;
  71416. };
  71417. /**
  71418. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  71419. */
  71420. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  71421. if (disableDepthRender === void 0) { disableDepthRender = false; }
  71422. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  71423. this._chromaticAberrationPostProcess = null;
  71424. this._highlightsPostProcess = null;
  71425. this._depthOfFieldPostProcess = null;
  71426. this._grainTexture.dispose();
  71427. if (disableDepthRender)
  71428. this._scene.disableDepthRenderer();
  71429. };
  71430. // colors shifting and distortion
  71431. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  71432. var _this = this;
  71433. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  71434. [], // samplers
  71435. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  71436. this._chromaticAberrationPostProcess.onApply = function (effect) {
  71437. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  71438. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  71439. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  71440. effect.setFloat('radialIntensity', 1);
  71441. effect.setFloat2('direction', 17, 17);
  71442. effect.setFloat2('centerPosition', 0.5, 0.5);
  71443. };
  71444. };
  71445. // highlights enhancing
  71446. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  71447. var _this = this;
  71448. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  71449. [], // samplers
  71450. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  71451. this._highlightsPostProcess.onApply = function (effect) {
  71452. effect.setFloat('gain', _this._highlightsGain);
  71453. effect.setFloat('threshold', _this._highlightsThreshold);
  71454. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  71455. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  71456. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  71457. };
  71458. };
  71459. // colors shifting and distortion
  71460. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  71461. var _this = this;
  71462. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  71463. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  71464. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  71465. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  71466. this._depthOfFieldPostProcess.onApply = function (effect) {
  71467. effect.setTexture("depthSampler", _this._depthTexture);
  71468. effect.setTexture("grainSampler", _this._grainTexture);
  71469. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  71470. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  71471. effect.setFloat('grain_amount', _this._grainAmount);
  71472. effect.setBool('blur_noise', _this._blurNoise);
  71473. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  71474. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  71475. effect.setFloat('distortion', _this._distortion);
  71476. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  71477. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  71478. effect.setFloat('aperture', _this._dofAperture);
  71479. effect.setFloat('darken', _this._dofDarken);
  71480. effect.setFloat('edge_blur', _this._edgeBlur);
  71481. effect.setBool('highlights', (_this._highlightsGain !== -1));
  71482. if (_this._scene.activeCamera) {
  71483. effect.setFloat('near', _this._scene.activeCamera.minZ);
  71484. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  71485. }
  71486. };
  71487. };
  71488. // creates a black and white random noise texture, 512x512
  71489. LensRenderingPipeline.prototype._createGrainTexture = function () {
  71490. var size = 512;
  71491. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  71492. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  71493. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  71494. var context = this._grainTexture.getContext();
  71495. var rand = function (min, max) {
  71496. return Math.random() * (max - min) + min;
  71497. };
  71498. var value;
  71499. for (var x = 0; x < size; x++) {
  71500. for (var y = 0; y < size; y++) {
  71501. value = Math.floor(rand(0.42, 0.58) * 255);
  71502. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  71503. context.fillRect(x, y, 1, 1);
  71504. }
  71505. }
  71506. this._grainTexture.update(false);
  71507. };
  71508. return LensRenderingPipeline;
  71509. }(BABYLON.PostProcessRenderPipeline));
  71510. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  71511. })(BABYLON || (BABYLON = {}));
  71512. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  71513. "use strict";
  71514. var BABYLON;
  71515. (function (BABYLON) {
  71516. var StandardRenderingPipeline = /** @class */ (function (_super) {
  71517. __extends(StandardRenderingPipeline, _super);
  71518. /**
  71519. * @constructor
  71520. * @param {string} name - The rendering pipeline name
  71521. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  71522. * @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)
  71523. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  71524. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  71525. */
  71526. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  71527. if (originalPostProcess === void 0) { originalPostProcess = null; }
  71528. var _this = _super.call(this, scene.getEngine(), name) || this;
  71529. _this.downSampleX4PostProcess = null;
  71530. _this.brightPassPostProcess = null;
  71531. _this.blurHPostProcesses = [];
  71532. _this.blurVPostProcesses = [];
  71533. _this.textureAdderPostProcess = null;
  71534. _this.volumetricLightPostProcess = null;
  71535. _this.volumetricLightSmoothXPostProcess = null;
  71536. _this.volumetricLightSmoothYPostProcess = null;
  71537. _this.volumetricLightMergePostProces = null;
  71538. _this.volumetricLightFinalPostProcess = null;
  71539. _this.luminancePostProcess = null;
  71540. _this.luminanceDownSamplePostProcesses = [];
  71541. _this.hdrPostProcess = null;
  71542. _this.textureAdderFinalPostProcess = null;
  71543. _this.lensFlareFinalPostProcess = null;
  71544. _this.hdrFinalPostProcess = null;
  71545. _this.lensFlarePostProcess = null;
  71546. _this.lensFlareComposePostProcess = null;
  71547. _this.motionBlurPostProcess = null;
  71548. _this.depthOfFieldPostProcess = null;
  71549. // Values
  71550. _this.brightThreshold = 1.0;
  71551. _this.blurWidth = 512.0;
  71552. _this.horizontalBlur = false;
  71553. _this.exposure = 1.0;
  71554. _this.lensTexture = null;
  71555. _this.volumetricLightCoefficient = 0.2;
  71556. _this.volumetricLightPower = 4.0;
  71557. _this.volumetricLightBlurScale = 64.0;
  71558. _this.sourceLight = null;
  71559. _this.hdrMinimumLuminance = 1.0;
  71560. _this.hdrDecreaseRate = 0.5;
  71561. _this.hdrIncreaseRate = 0.5;
  71562. _this.lensColorTexture = null;
  71563. _this.lensFlareStrength = 20.0;
  71564. _this.lensFlareGhostDispersal = 1.4;
  71565. _this.lensFlareHaloWidth = 0.7;
  71566. _this.lensFlareDistortionStrength = 16.0;
  71567. _this.lensStarTexture = null;
  71568. _this.lensFlareDirtTexture = null;
  71569. _this.depthOfFieldDistance = 10.0;
  71570. _this.depthOfFieldBlurWidth = 64.0;
  71571. _this.motionStrength = 1.0;
  71572. // IAnimatable
  71573. _this.animations = [];
  71574. _this._currentDepthOfFieldSource = null;
  71575. _this._hdrCurrentLuminance = 1.0;
  71576. // Getters and setters
  71577. _this._bloomEnabled = true;
  71578. _this._depthOfFieldEnabled = false;
  71579. _this._vlsEnabled = false;
  71580. _this._lensFlareEnabled = false;
  71581. _this._hdrEnabled = false;
  71582. _this._motionBlurEnabled = false;
  71583. _this._motionBlurSamples = 64.0;
  71584. _this._volumetricLightStepsCount = 50.0;
  71585. _this._cameras = cameras || [];
  71586. // Initialize
  71587. _this._scene = scene;
  71588. _this._basePostProcess = originalPostProcess;
  71589. _this._ratio = ratio;
  71590. // Misc
  71591. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  71592. // Finish
  71593. scene.postProcessRenderPipelineManager.addPipeline(_this);
  71594. _this._buildPipeline();
  71595. return _this;
  71596. }
  71597. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  71598. get: function () {
  71599. return this._bloomEnabled;
  71600. },
  71601. set: function (enabled) {
  71602. if (this._bloomEnabled === enabled) {
  71603. return;
  71604. }
  71605. this._bloomEnabled = enabled;
  71606. this._buildPipeline();
  71607. },
  71608. enumerable: true,
  71609. configurable: true
  71610. });
  71611. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  71612. get: function () {
  71613. return this._depthOfFieldEnabled;
  71614. },
  71615. set: function (enabled) {
  71616. if (this._depthOfFieldEnabled === enabled) {
  71617. return;
  71618. }
  71619. this._depthOfFieldEnabled = enabled;
  71620. this._buildPipeline();
  71621. },
  71622. enumerable: true,
  71623. configurable: true
  71624. });
  71625. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  71626. get: function () {
  71627. return this._lensFlareEnabled;
  71628. },
  71629. set: function (enabled) {
  71630. if (this._lensFlareEnabled === enabled) {
  71631. return;
  71632. }
  71633. this._lensFlareEnabled = enabled;
  71634. this._buildPipeline();
  71635. },
  71636. enumerable: true,
  71637. configurable: true
  71638. });
  71639. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  71640. get: function () {
  71641. return this._hdrEnabled;
  71642. },
  71643. set: function (enabled) {
  71644. if (this._hdrEnabled === enabled) {
  71645. return;
  71646. }
  71647. this._hdrEnabled = enabled;
  71648. this._buildPipeline();
  71649. },
  71650. enumerable: true,
  71651. configurable: true
  71652. });
  71653. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  71654. get: function () {
  71655. return this._vlsEnabled;
  71656. },
  71657. set: function (enabled) {
  71658. if (this._vlsEnabled === enabled) {
  71659. return;
  71660. }
  71661. if (enabled) {
  71662. var geometry = this._scene.enableGeometryBufferRenderer();
  71663. if (!geometry) {
  71664. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  71665. return;
  71666. }
  71667. }
  71668. this._vlsEnabled = enabled;
  71669. this._buildPipeline();
  71670. },
  71671. enumerable: true,
  71672. configurable: true
  71673. });
  71674. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  71675. get: function () {
  71676. return this._motionBlurEnabled;
  71677. },
  71678. set: function (enabled) {
  71679. if (this._motionBlurEnabled === enabled) {
  71680. return;
  71681. }
  71682. this._motionBlurEnabled = enabled;
  71683. this._buildPipeline();
  71684. },
  71685. enumerable: true,
  71686. configurable: true
  71687. });
  71688. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  71689. get: function () {
  71690. return this._volumetricLightStepsCount;
  71691. },
  71692. set: function (count) {
  71693. if (this.volumetricLightPostProcess) {
  71694. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  71695. }
  71696. this._volumetricLightStepsCount = count;
  71697. },
  71698. enumerable: true,
  71699. configurable: true
  71700. });
  71701. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  71702. get: function () {
  71703. return this._motionBlurSamples;
  71704. },
  71705. set: function (samples) {
  71706. if (this.motionBlurPostProcess) {
  71707. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  71708. }
  71709. this._motionBlurSamples = samples;
  71710. },
  71711. enumerable: true,
  71712. configurable: true
  71713. });
  71714. StandardRenderingPipeline.prototype._buildPipeline = function () {
  71715. var _this = this;
  71716. var ratio = this._ratio;
  71717. var scene = this._scene;
  71718. this._disposePostProcesses();
  71719. this._reset();
  71720. // Create pass post-process
  71721. if (!this._basePostProcess) {
  71722. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  71723. this.originalPostProcess.onApply = function (effect) {
  71724. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  71725. };
  71726. }
  71727. else {
  71728. this.originalPostProcess = this._basePostProcess;
  71729. }
  71730. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  71731. this._currentDepthOfFieldSource = this.originalPostProcess;
  71732. if (this._vlsEnabled) {
  71733. // Create volumetric light
  71734. this._createVolumetricLightPostProcess(scene, ratio);
  71735. // Create volumetric light final post-process
  71736. 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);
  71737. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  71738. }
  71739. if (this._bloomEnabled) {
  71740. // Create down sample X4 post-process
  71741. this._createDownSampleX4PostProcess(scene, ratio / 2);
  71742. // Create bright pass post-process
  71743. this._createBrightPassPostProcess(scene, ratio / 2);
  71744. // Create gaussian blur post-processes (down sampling blurs)
  71745. this._createBlurPostProcesses(scene, ratio / 4, 1);
  71746. // Create texture adder post-process
  71747. this._createTextureAdderPostProcess(scene, ratio);
  71748. // Create depth-of-field source post-process
  71749. 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);
  71750. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  71751. }
  71752. if (this._lensFlareEnabled) {
  71753. // Create lens flare post-process
  71754. this._createLensFlarePostProcess(scene, ratio);
  71755. // Create depth-of-field source post-process post lens-flare and disable it now
  71756. 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);
  71757. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  71758. }
  71759. if (this._hdrEnabled) {
  71760. // Create luminance
  71761. this._createLuminancePostProcesses(scene, this._floatTextureType);
  71762. // Create HDR
  71763. this._createHdrPostProcess(scene, ratio);
  71764. // Create depth-of-field source post-process post hdr and disable it now
  71765. 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);
  71766. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  71767. }
  71768. if (this._depthOfFieldEnabled) {
  71769. // Create gaussian blur used by depth-of-field
  71770. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  71771. // Create depth-of-field post-process
  71772. this._createDepthOfFieldPostProcess(scene, ratio);
  71773. }
  71774. if (this._motionBlurEnabled) {
  71775. // Create motion blur post-process
  71776. this._createMotionBlurPostProcess(scene, ratio);
  71777. }
  71778. if (this._cameras !== null) {
  71779. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  71780. }
  71781. };
  71782. // Down Sample X4 Post-Processs
  71783. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  71784. var _this = this;
  71785. var downSampleX4Offsets = new Array(32);
  71786. 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);
  71787. this.downSampleX4PostProcess.onApply = function (effect) {
  71788. var id = 0;
  71789. var width = _this.downSampleX4PostProcess.width;
  71790. var height = _this.downSampleX4PostProcess.height;
  71791. for (var i = -2; i < 2; i++) {
  71792. for (var j = -2; j < 2; j++) {
  71793. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  71794. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  71795. id += 2;
  71796. }
  71797. }
  71798. effect.setArray2("dsOffsets", downSampleX4Offsets);
  71799. };
  71800. // Add to pipeline
  71801. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  71802. };
  71803. // Brightpass Post-Process
  71804. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  71805. var _this = this;
  71806. var brightOffsets = new Array(8);
  71807. 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);
  71808. this.brightPassPostProcess.onApply = function (effect) {
  71809. var sU = (1.0 / _this.brightPassPostProcess.width);
  71810. var sV = (1.0 / _this.brightPassPostProcess.height);
  71811. brightOffsets[0] = -0.5 * sU;
  71812. brightOffsets[1] = 0.5 * sV;
  71813. brightOffsets[2] = 0.5 * sU;
  71814. brightOffsets[3] = 0.5 * sV;
  71815. brightOffsets[4] = -0.5 * sU;
  71816. brightOffsets[5] = -0.5 * sV;
  71817. brightOffsets[6] = 0.5 * sU;
  71818. brightOffsets[7] = -0.5 * sV;
  71819. effect.setArray2("dsOffsets", brightOffsets);
  71820. effect.setFloat("brightThreshold", _this.brightThreshold);
  71821. };
  71822. // Add to pipeline
  71823. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  71824. };
  71825. // Create blur H&V post-processes
  71826. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  71827. var _this = this;
  71828. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  71829. var engine = scene.getEngine();
  71830. 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);
  71831. 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);
  71832. blurX.onActivateObservable.add(function () {
  71833. var dw = blurX.width / engine.getRenderWidth();
  71834. blurX.kernel = _this[blurWidthKey] * dw;
  71835. });
  71836. blurY.onActivateObservable.add(function () {
  71837. var dw = blurY.height / engine.getRenderHeight();
  71838. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  71839. });
  71840. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  71841. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  71842. this.blurHPostProcesses.push(blurX);
  71843. this.blurVPostProcesses.push(blurY);
  71844. };
  71845. // Create texture adder post-process
  71846. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  71847. var _this = this;
  71848. 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);
  71849. this.textureAdderPostProcess.onApply = function (effect) {
  71850. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  71851. effect.setTexture("lensSampler", _this.lensTexture);
  71852. effect.setFloat("exposure", _this.exposure);
  71853. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  71854. };
  71855. // Add to pipeline
  71856. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  71857. };
  71858. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  71859. var _this = this;
  71860. var geometryRenderer = scene.enableGeometryBufferRenderer();
  71861. geometryRenderer.enablePosition = true;
  71862. var geometry = geometryRenderer.getGBuffer();
  71863. // Base post-process
  71864. 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));
  71865. var depthValues = BABYLON.Vector2.Zero();
  71866. this.volumetricLightPostProcess.onApply = function (effect) {
  71867. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  71868. var generator = _this.sourceLight.getShadowGenerator();
  71869. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  71870. effect.setTexture("positionSampler", geometry.textures[2]);
  71871. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  71872. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  71873. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  71874. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  71875. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  71876. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  71877. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  71878. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  71879. effect.setVector2("depthValues", depthValues);
  71880. }
  71881. };
  71882. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  71883. // Smooth
  71884. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  71885. // Merge
  71886. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  71887. this.volumetricLightMergePostProces.onApply = function (effect) {
  71888. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  71889. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  71890. };
  71891. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  71892. };
  71893. // Create luminance
  71894. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  71895. var _this = this;
  71896. // Create luminance
  71897. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  71898. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  71899. var offsets = [];
  71900. this.luminancePostProcess.onApply = function (effect) {
  71901. var sU = (1.0 / _this.luminancePostProcess.width);
  71902. var sV = (1.0 / _this.luminancePostProcess.height);
  71903. offsets[0] = -0.5 * sU;
  71904. offsets[1] = 0.5 * sV;
  71905. offsets[2] = 0.5 * sU;
  71906. offsets[3] = 0.5 * sV;
  71907. offsets[4] = -0.5 * sU;
  71908. offsets[5] = -0.5 * sV;
  71909. offsets[6] = 0.5 * sU;
  71910. offsets[7] = -0.5 * sV;
  71911. effect.setArray2("lumOffsets", offsets);
  71912. };
  71913. // Add to pipeline
  71914. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  71915. // Create down sample luminance
  71916. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  71917. var size = Math.pow(3, i);
  71918. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  71919. if (i === 0) {
  71920. defines += "#define FINAL_DOWN_SAMPLER";
  71921. }
  71922. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  71923. this.luminanceDownSamplePostProcesses.push(postProcess);
  71924. }
  71925. // Create callbacks and add effects
  71926. var lastLuminance = this.luminancePostProcess;
  71927. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  71928. var downSampleOffsets = new Array(18);
  71929. pp.onApply = function (effect) {
  71930. if (!lastLuminance) {
  71931. return;
  71932. }
  71933. var id = 0;
  71934. for (var x = -1; x < 2; x++) {
  71935. for (var y = -1; y < 2; y++) {
  71936. downSampleOffsets[id] = x / lastLuminance.width;
  71937. downSampleOffsets[id + 1] = y / lastLuminance.height;
  71938. id += 2;
  71939. }
  71940. }
  71941. effect.setArray2("dsOffsets", downSampleOffsets);
  71942. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  71943. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  71944. lastLuminance = _this.luminancePostProcess;
  71945. }
  71946. else {
  71947. lastLuminance = pp;
  71948. }
  71949. };
  71950. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  71951. pp.onAfterRender = function (effect) {
  71952. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  71953. 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);
  71954. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  71955. };
  71956. }
  71957. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  71958. });
  71959. };
  71960. // Create HDR post-process
  71961. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  71962. var _this = this;
  71963. 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);
  71964. var outputLiminance = 1;
  71965. var time = 0;
  71966. var lastTime = 0;
  71967. this.hdrPostProcess.onApply = function (effect) {
  71968. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  71969. time += scene.getEngine().getDeltaTime();
  71970. if (outputLiminance < 0) {
  71971. outputLiminance = _this._hdrCurrentLuminance;
  71972. }
  71973. else {
  71974. var dt = (lastTime - time) / 1000.0;
  71975. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  71976. outputLiminance += _this.hdrDecreaseRate * dt;
  71977. }
  71978. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  71979. outputLiminance -= _this.hdrIncreaseRate * dt;
  71980. }
  71981. else {
  71982. outputLiminance = _this._hdrCurrentLuminance;
  71983. }
  71984. }
  71985. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  71986. effect.setFloat("averageLuminance", outputLiminance);
  71987. lastTime = time;
  71988. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  71989. };
  71990. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  71991. };
  71992. // Create lens flare post-process
  71993. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  71994. var _this = this;
  71995. 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);
  71996. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  71997. this._createBlurPostProcesses(scene, ratio / 4, 2);
  71998. 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);
  71999. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  72000. var resolution = new BABYLON.Vector2(0, 0);
  72001. // Lens flare
  72002. this.lensFlarePostProcess.onApply = function (effect) {
  72003. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  72004. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  72005. effect.setFloat("strength", _this.lensFlareStrength);
  72006. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  72007. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  72008. // Shift
  72009. resolution.x = _this.lensFlarePostProcess.width;
  72010. resolution.y = _this.lensFlarePostProcess.height;
  72011. effect.setVector2("resolution", resolution);
  72012. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  72013. };
  72014. // Compose
  72015. 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);
  72016. 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);
  72017. this.lensFlareComposePostProcess.onApply = function (effect) {
  72018. if (!_this._scene.activeCamera) {
  72019. return;
  72020. }
  72021. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  72022. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  72023. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  72024. // Lens start rotation matrix
  72025. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  72026. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  72027. 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));
  72028. camRot *= 4.0;
  72029. 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);
  72030. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  72031. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  72032. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  72033. };
  72034. };
  72035. // Create depth-of-field post-process
  72036. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  72037. var _this = this;
  72038. 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);
  72039. this.depthOfFieldPostProcess.onApply = function (effect) {
  72040. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  72041. effect.setTexture("depthSampler", _this._getDepthTexture());
  72042. effect.setFloat("distance", _this.depthOfFieldDistance);
  72043. };
  72044. // Add to pipeline
  72045. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  72046. };
  72047. // Create motion blur post-process
  72048. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  72049. var _this = this;
  72050. 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);
  72051. var motionScale = 0;
  72052. var prevViewProjection = BABYLON.Matrix.Identity();
  72053. var invViewProjection = BABYLON.Matrix.Identity();
  72054. var viewProjection = BABYLON.Matrix.Identity();
  72055. var screenSize = BABYLON.Vector2.Zero();
  72056. this.motionBlurPostProcess.onApply = function (effect) {
  72057. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  72058. viewProjection.invertToRef(invViewProjection);
  72059. effect.setMatrix("inverseViewProjection", invViewProjection);
  72060. effect.setMatrix("prevViewProjection", prevViewProjection);
  72061. prevViewProjection = viewProjection;
  72062. screenSize.x = _this.motionBlurPostProcess.width;
  72063. screenSize.y = _this.motionBlurPostProcess.height;
  72064. effect.setVector2("screenSize", screenSize);
  72065. motionScale = scene.getEngine().getFps() / 60.0;
  72066. effect.setFloat("motionScale", motionScale);
  72067. effect.setFloat("motionStrength", _this.motionStrength);
  72068. effect.setTexture("depthSampler", _this._getDepthTexture());
  72069. };
  72070. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  72071. };
  72072. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  72073. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  72074. var renderer = this._scene.enableGeometryBufferRenderer();
  72075. return renderer.getGBuffer().textures[0];
  72076. }
  72077. return this._scene.enableDepthRenderer().getDepthMap();
  72078. };
  72079. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  72080. for (var i = 0; i < this._cameras.length; i++) {
  72081. var camera = this._cameras[i];
  72082. if (this.originalPostProcess) {
  72083. this.originalPostProcess.dispose(camera);
  72084. }
  72085. if (this.downSampleX4PostProcess) {
  72086. this.downSampleX4PostProcess.dispose(camera);
  72087. }
  72088. if (this.brightPassPostProcess) {
  72089. this.brightPassPostProcess.dispose(camera);
  72090. }
  72091. if (this.textureAdderPostProcess) {
  72092. this.textureAdderPostProcess.dispose(camera);
  72093. }
  72094. if (this.textureAdderFinalPostProcess) {
  72095. this.textureAdderFinalPostProcess.dispose(camera);
  72096. }
  72097. if (this.volumetricLightPostProcess) {
  72098. this.volumetricLightPostProcess.dispose(camera);
  72099. }
  72100. if (this.volumetricLightSmoothXPostProcess) {
  72101. this.volumetricLightSmoothXPostProcess.dispose(camera);
  72102. }
  72103. if (this.volumetricLightSmoothYPostProcess) {
  72104. this.volumetricLightSmoothYPostProcess.dispose(camera);
  72105. }
  72106. if (this.volumetricLightMergePostProces) {
  72107. this.volumetricLightMergePostProces.dispose(camera);
  72108. }
  72109. if (this.volumetricLightFinalPostProcess) {
  72110. this.volumetricLightFinalPostProcess.dispose(camera);
  72111. }
  72112. if (this.lensFlarePostProcess) {
  72113. this.lensFlarePostProcess.dispose(camera);
  72114. }
  72115. if (this.lensFlareComposePostProcess) {
  72116. this.lensFlareComposePostProcess.dispose(camera);
  72117. }
  72118. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  72119. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  72120. }
  72121. if (this.luminancePostProcess) {
  72122. this.luminancePostProcess.dispose(camera);
  72123. }
  72124. if (this.hdrPostProcess) {
  72125. this.hdrPostProcess.dispose(camera);
  72126. }
  72127. if (this.hdrFinalPostProcess) {
  72128. this.hdrFinalPostProcess.dispose(camera);
  72129. }
  72130. if (this.depthOfFieldPostProcess) {
  72131. this.depthOfFieldPostProcess.dispose(camera);
  72132. }
  72133. if (this.motionBlurPostProcess) {
  72134. this.motionBlurPostProcess.dispose(camera);
  72135. }
  72136. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  72137. this.blurHPostProcesses[j].dispose(camera);
  72138. }
  72139. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  72140. this.blurVPostProcesses[j].dispose(camera);
  72141. }
  72142. }
  72143. this.originalPostProcess = null;
  72144. this.downSampleX4PostProcess = null;
  72145. this.brightPassPostProcess = null;
  72146. this.textureAdderPostProcess = null;
  72147. this.textureAdderFinalPostProcess = null;
  72148. this.volumetricLightPostProcess = null;
  72149. this.volumetricLightSmoothXPostProcess = null;
  72150. this.volumetricLightSmoothYPostProcess = null;
  72151. this.volumetricLightMergePostProces = null;
  72152. this.volumetricLightFinalPostProcess = null;
  72153. this.lensFlarePostProcess = null;
  72154. this.lensFlareComposePostProcess = null;
  72155. this.luminancePostProcess = null;
  72156. this.hdrPostProcess = null;
  72157. this.hdrFinalPostProcess = null;
  72158. this.depthOfFieldPostProcess = null;
  72159. this.motionBlurPostProcess = null;
  72160. this.luminanceDownSamplePostProcesses = [];
  72161. this.blurHPostProcesses = [];
  72162. this.blurVPostProcesses = [];
  72163. };
  72164. // Dispose
  72165. StandardRenderingPipeline.prototype.dispose = function () {
  72166. this._disposePostProcesses();
  72167. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  72168. _super.prototype.dispose.call(this);
  72169. };
  72170. // Serialize rendering pipeline
  72171. StandardRenderingPipeline.prototype.serialize = function () {
  72172. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  72173. serializationObject.customType = "StandardRenderingPipeline";
  72174. return serializationObject;
  72175. };
  72176. /**
  72177. * Static members
  72178. */
  72179. // Parse serialized pipeline
  72180. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  72181. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  72182. };
  72183. // Luminance steps
  72184. StandardRenderingPipeline.LuminanceSteps = 6;
  72185. __decorate([
  72186. BABYLON.serialize()
  72187. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  72188. __decorate([
  72189. BABYLON.serialize()
  72190. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  72191. __decorate([
  72192. BABYLON.serialize()
  72193. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  72194. __decorate([
  72195. BABYLON.serialize()
  72196. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  72197. __decorate([
  72198. BABYLON.serializeAsTexture("lensTexture")
  72199. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  72200. __decorate([
  72201. BABYLON.serialize()
  72202. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  72203. __decorate([
  72204. BABYLON.serialize()
  72205. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  72206. __decorate([
  72207. BABYLON.serialize()
  72208. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  72209. __decorate([
  72210. BABYLON.serialize()
  72211. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  72212. __decorate([
  72213. BABYLON.serialize()
  72214. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  72215. __decorate([
  72216. BABYLON.serialize()
  72217. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  72218. __decorate([
  72219. BABYLON.serializeAsTexture("lensColorTexture")
  72220. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  72221. __decorate([
  72222. BABYLON.serialize()
  72223. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  72224. __decorate([
  72225. BABYLON.serialize()
  72226. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  72227. __decorate([
  72228. BABYLON.serialize()
  72229. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  72230. __decorate([
  72231. BABYLON.serialize()
  72232. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  72233. __decorate([
  72234. BABYLON.serializeAsTexture("lensStarTexture")
  72235. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  72236. __decorate([
  72237. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  72238. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  72239. __decorate([
  72240. BABYLON.serialize()
  72241. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  72242. __decorate([
  72243. BABYLON.serialize()
  72244. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  72245. __decorate([
  72246. BABYLON.serialize()
  72247. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  72248. __decorate([
  72249. BABYLON.serialize()
  72250. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  72251. __decorate([
  72252. BABYLON.serialize()
  72253. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  72254. __decorate([
  72255. BABYLON.serialize()
  72256. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  72257. __decorate([
  72258. BABYLON.serialize()
  72259. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  72260. __decorate([
  72261. BABYLON.serialize()
  72262. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  72263. __decorate([
  72264. BABYLON.serialize()
  72265. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  72266. __decorate([
  72267. BABYLON.serialize()
  72268. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  72269. __decorate([
  72270. BABYLON.serialize()
  72271. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  72272. __decorate([
  72273. BABYLON.serialize()
  72274. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  72275. return StandardRenderingPipeline;
  72276. }(BABYLON.PostProcessRenderPipeline));
  72277. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  72278. })(BABYLON || (BABYLON = {}));
  72279. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  72280. "use strict";
  72281. var BABYLON;
  72282. (function (BABYLON) {
  72283. var FxaaPostProcess = /** @class */ (function (_super) {
  72284. __extends(FxaaPostProcess, _super);
  72285. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  72286. if (camera === void 0) { camera = null; }
  72287. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72288. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  72289. _this.onApplyObservable.add(function (effect) {
  72290. var texelSize = _this.texelSize;
  72291. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  72292. });
  72293. return _this;
  72294. }
  72295. return FxaaPostProcess;
  72296. }(BABYLON.PostProcess));
  72297. BABYLON.FxaaPostProcess = FxaaPostProcess;
  72298. })(BABYLON || (BABYLON = {}));
  72299. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  72300. "use strict";
  72301. var BABYLON;
  72302. (function (BABYLON) {
  72303. /**
  72304. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  72305. */
  72306. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  72307. __extends(ChromaticAberrationPostProcess, _super);
  72308. /**
  72309. * Creates a new instance ChromaticAberrationPostProcess
  72310. * @param name The name of the effect.
  72311. * @param screenWidth The width of the screen to apply the effect on.
  72312. * @param screenHeight The height of the screen to apply the effect on.
  72313. * @param options The required width/height ratio to downsize to before computing the render pass.
  72314. * @param camera The camera to apply the render pass to.
  72315. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  72316. * @param engine The engine which the post process will be applied. (default: current engine)
  72317. * @param reusable If the post process can be reused on the same frame. (default: false)
  72318. * @param textureType Type of textures used when performing the post process. (default: 0)
  72319. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  72320. */
  72321. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  72322. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72323. if (blockCompilation === void 0) { blockCompilation = false; }
  72324. var _this = _super.call(this, name, "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  72325. /**
  72326. * The amount of seperation of rgb channels (default: 30)
  72327. */
  72328. _this.aberrationAmount = 30;
  72329. /**
  72330. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  72331. */
  72332. _this.radialIntensity = 0;
  72333. /**
  72334. * The normilized direction in which the rgb channels should be seperated. If set to 0,0 radial direction will be used. (default: Vector2(0.707,0.707))
  72335. */
  72336. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  72337. /**
  72338. * The center position where the radialIntensity should be around. [0.5,0.5 is center of screen, 1,1 is top right corder] (default: Vector2(0.5 ,0.5))
  72339. */
  72340. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  72341. _this.onApplyObservable.add(function (effect) {
  72342. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  72343. effect.setFloat('screen_width', screenWidth);
  72344. effect.setFloat('screen_height', screenHeight);
  72345. effect.setFloat('radialIntensity', _this.radialIntensity);
  72346. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  72347. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  72348. });
  72349. return _this;
  72350. }
  72351. return ChromaticAberrationPostProcess;
  72352. }(BABYLON.PostProcess));
  72353. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  72354. })(BABYLON || (BABYLON = {}));
  72355. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  72356. "use strict";
  72357. var BABYLON;
  72358. (function (BABYLON) {
  72359. /**
  72360. * The GrainPostProcess adds noise to the image at mid luminance levels
  72361. */
  72362. var GrainPostProcess = /** @class */ (function (_super) {
  72363. __extends(GrainPostProcess, _super);
  72364. /**
  72365. * Creates a new instance of @see GrainPostProcess
  72366. * @param name The name of the effect.
  72367. * @param options The required width/height ratio to downsize to before computing the render pass.
  72368. * @param camera The camera to apply the render pass to.
  72369. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  72370. * @param engine The engine which the post process will be applied. (default: current engine)
  72371. * @param reusable If the post process can be reused on the same frame. (default: false)
  72372. * @param textureType Type of textures used when performing the post process. (default: 0)
  72373. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  72374. */
  72375. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  72376. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72377. if (blockCompilation === void 0) { blockCompilation = false; }
  72378. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  72379. /**
  72380. * The intensity of the grain added (default: 30)
  72381. */
  72382. _this.intensity = 30;
  72383. /**
  72384. * If the grain should be randomized on every frame
  72385. */
  72386. _this.animated = false;
  72387. _this.onApplyObservable.add(function (effect) {
  72388. effect.setFloat('intensity', _this.intensity);
  72389. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  72390. });
  72391. return _this;
  72392. }
  72393. return GrainPostProcess;
  72394. }(BABYLON.PostProcess));
  72395. BABYLON.GrainPostProcess = GrainPostProcess;
  72396. })(BABYLON || (BABYLON = {}));
  72397. //# sourceMappingURL=babylon.grainPostProcess.js.map
  72398. "use strict";
  72399. var BABYLON;
  72400. (function (BABYLON) {
  72401. /**
  72402. * The SharpenPostProcess applies a sharpen kernel to every pixel
  72403. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  72404. */
  72405. var SharpenPostProcess = /** @class */ (function (_super) {
  72406. __extends(SharpenPostProcess, _super);
  72407. /**
  72408. * Creates a new instance ConvolutionPostProcess
  72409. * @param name The name of the effect.
  72410. * @param options The required width/height ratio to downsize to before computing the render pass.
  72411. * @param camera The camera to apply the render pass to.
  72412. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  72413. * @param engine The engine which the post process will be applied. (default: current engine)
  72414. * @param reusable If the post process can be reused on the same frame. (default: false)
  72415. * @param textureType Type of textures used when performing the post process. (default: 0)
  72416. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  72417. */
  72418. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  72419. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72420. if (blockCompilation === void 0) { blockCompilation = false; }
  72421. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  72422. /**
  72423. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  72424. */
  72425. _this.colorAmount = 1.0;
  72426. /**
  72427. * How much sharpness should be applied (default: 0.3)
  72428. */
  72429. _this.edgeAmount = 0.3;
  72430. _this.onApply = function (effect) {
  72431. effect.setFloat2("screenSize", _this.width, _this.height);
  72432. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  72433. };
  72434. return _this;
  72435. }
  72436. return SharpenPostProcess;
  72437. }(BABYLON.PostProcess));
  72438. BABYLON.SharpenPostProcess = SharpenPostProcess;
  72439. })(BABYLON || (BABYLON = {}));
  72440. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  72441. "use strict";
  72442. var BABYLON;
  72443. (function (BABYLON) {
  72444. /**
  72445. * The Blur Post Process which blurs an image based on a kernel and direction.
  72446. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  72447. */
  72448. var BlurPostProcess = /** @class */ (function (_super) {
  72449. __extends(BlurPostProcess, _super);
  72450. /**
  72451. * Creates a new instance BlurPostProcess
  72452. * @param name The name of the effect.
  72453. * @param direction The direction in which to blur the image.
  72454. * @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.
  72455. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  72456. * @param camera The camera to apply the render pass to.
  72457. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  72458. * @param engine The engine which the post process will be applied. (default: current engine)
  72459. * @param reusable If the post process can be reused on the same frame. (default: false)
  72460. * @param textureType Type of textures used when performing the post process. (default: 0)
  72461. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  72462. */
  72463. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  72464. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  72465. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72466. if (defines === void 0) { defines = ""; }
  72467. if (blockCompilation === void 0) { blockCompilation = false; }
  72468. 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;
  72469. _this.direction = direction;
  72470. _this.blockCompilation = blockCompilation;
  72471. _this._packedFloat = false;
  72472. _this._staticDefines = "";
  72473. _this._staticDefines = defines;
  72474. _this.onApplyObservable.add(function (effect) {
  72475. if (_this._outputTexture) {
  72476. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  72477. }
  72478. else {
  72479. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  72480. }
  72481. });
  72482. _this.kernel = kernel;
  72483. return _this;
  72484. }
  72485. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  72486. /**
  72487. * Gets the length in pixels of the blur sample region
  72488. */
  72489. get: function () {
  72490. return this._idealKernel;
  72491. },
  72492. /**
  72493. * Sets the length in pixels of the blur sample region
  72494. */
  72495. set: function (v) {
  72496. if (this._idealKernel === v) {
  72497. return;
  72498. }
  72499. v = Math.max(v, 1);
  72500. this._idealKernel = v;
  72501. this._kernel = this._nearestBestKernel(v);
  72502. if (!this.blockCompilation) {
  72503. this._updateParameters();
  72504. }
  72505. },
  72506. enumerable: true,
  72507. configurable: true
  72508. });
  72509. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  72510. /**
  72511. * Gets wether or not the blur is unpacking/repacking floats
  72512. */
  72513. get: function () {
  72514. return this._packedFloat;
  72515. },
  72516. /**
  72517. * Sets wether or not the blur needs to unpack/repack floats
  72518. */
  72519. set: function (v) {
  72520. if (this._packedFloat === v) {
  72521. return;
  72522. }
  72523. this._packedFloat = v;
  72524. if (!this.blockCompilation) {
  72525. this._updateParameters();
  72526. }
  72527. },
  72528. enumerable: true,
  72529. configurable: true
  72530. });
  72531. /**
  72532. * Updates the effect with the current post process compile time values and recompiles the shader.
  72533. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  72534. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  72535. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  72536. * @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
  72537. * @param onCompiled Called when the shader has been compiled.
  72538. * @param onError Called if there is an error when compiling a shader.
  72539. */
  72540. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  72541. if (defines === void 0) { defines = null; }
  72542. if (uniforms === void 0) { uniforms = null; }
  72543. if (samplers === void 0) { samplers = null; }
  72544. this._updateParameters(onCompiled, onError);
  72545. };
  72546. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  72547. // Generate sampling offsets and weights
  72548. var N = this._kernel;
  72549. var centerIndex = (N - 1) / 2;
  72550. // Generate Gaussian sampling weights over kernel
  72551. var offsets = [];
  72552. var weights = [];
  72553. var totalWeight = 0;
  72554. for (var i = 0; i < N; i++) {
  72555. var u = i / (N - 1);
  72556. var w = this._gaussianWeight(u * 2.0 - 1);
  72557. offsets[i] = (i - centerIndex);
  72558. weights[i] = w;
  72559. totalWeight += w;
  72560. }
  72561. // Normalize weights
  72562. for (var i = 0; i < weights.length; i++) {
  72563. weights[i] /= totalWeight;
  72564. }
  72565. // Optimize: combine samples to take advantage of hardware linear sampling
  72566. // Walk from left to center, combining pairs (symmetrically)
  72567. var linearSamplingWeights = [];
  72568. var linearSamplingOffsets = [];
  72569. var linearSamplingMap = [];
  72570. for (var i = 0; i <= centerIndex; i += 2) {
  72571. var j = Math.min(i + 1, Math.floor(centerIndex));
  72572. var singleCenterSample = i === j;
  72573. if (singleCenterSample) {
  72574. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  72575. }
  72576. else {
  72577. var sharedCell = j === centerIndex;
  72578. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  72579. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  72580. if (offsetLinear === 0) {
  72581. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  72582. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  72583. }
  72584. else {
  72585. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  72586. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  72587. }
  72588. }
  72589. }
  72590. for (var i = 0; i < linearSamplingMap.length; i++) {
  72591. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  72592. linearSamplingWeights[i] = linearSamplingMap[i].w;
  72593. }
  72594. // Replace with optimized
  72595. offsets = linearSamplingOffsets;
  72596. weights = linearSamplingWeights;
  72597. // Generate shaders
  72598. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  72599. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  72600. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  72601. var defines = "";
  72602. defines += this._staticDefines;
  72603. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  72604. if (this._staticDefines.indexOf("DOF") != -1) {
  72605. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  72606. varyingCount--;
  72607. }
  72608. for (var i = 0; i < varyingCount; i++) {
  72609. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  72610. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  72611. }
  72612. var depCount = 0;
  72613. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  72614. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  72615. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  72616. depCount++;
  72617. }
  72618. if (this.packedFloat) {
  72619. defines += "#define PACKEDFLOAT 1";
  72620. }
  72621. this.blockCompilation = false;
  72622. _super.prototype.updateEffect.call(this, defines, null, null, {
  72623. varyingCount: varyingCount,
  72624. depCount: depCount
  72625. }, onCompiled, onError);
  72626. };
  72627. /**
  72628. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  72629. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  72630. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  72631. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  72632. * The gaps between physical kernels are compensated for in the weighting of the samples
  72633. * @param idealKernel Ideal blur kernel.
  72634. * @return Nearest best kernel.
  72635. */
  72636. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  72637. var v = Math.round(idealKernel);
  72638. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  72639. var k = _a[_i];
  72640. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  72641. return Math.max(k, 3);
  72642. }
  72643. }
  72644. return Math.max(v, 3);
  72645. };
  72646. /**
  72647. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  72648. * @param x The point on the Gaussian distribution to sample.
  72649. * @return the value of the Gaussian function at x.
  72650. */
  72651. BlurPostProcess.prototype._gaussianWeight = function (x) {
  72652. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  72653. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  72654. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  72655. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  72656. // truncated at around 1.3% of peak strength.
  72657. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  72658. var sigma = (1 / 3);
  72659. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  72660. var exponent = -((x * x) / (2.0 * sigma * sigma));
  72661. var weight = (1.0 / denominator) * Math.exp(exponent);
  72662. return weight;
  72663. };
  72664. /**
  72665. * Generates a string that can be used as a floating point number in GLSL.
  72666. * @param x Value to print.
  72667. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  72668. * @return GLSL float string.
  72669. */
  72670. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  72671. if (decimalFigures === void 0) { decimalFigures = 8; }
  72672. return x.toFixed(decimalFigures).replace(/0+$/, '');
  72673. };
  72674. return BlurPostProcess;
  72675. }(BABYLON.PostProcess));
  72676. BABYLON.BlurPostProcess = BlurPostProcess;
  72677. })(BABYLON || (BABYLON = {}));
  72678. //# sourceMappingURL=babylon.blurPostProcess.js.map
  72679. "use strict";
  72680. var BABYLON;
  72681. (function (BABYLON) {
  72682. /**
  72683. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  72684. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  72685. * based on samples that have a large difference in distance than the center pixel.
  72686. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  72687. */
  72688. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  72689. __extends(DepthOfFieldBlurPostProcess, _super);
  72690. /**
  72691. * Creates a new instance CircleOfConfusionPostProcess
  72692. * @param name The name of the effect.
  72693. * @param scene The scene the effect belongs to.
  72694. * @param direction The direction the blur should be applied.
  72695. * @param kernel The size of the kernel used to blur.
  72696. * @param options The required width/height ratio to downsize to before computing the render pass.
  72697. * @param camera The camera to apply the render pass to.
  72698. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  72699. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  72700. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  72701. * @param engine The engine which the post process will be applied. (default: current engine)
  72702. * @param reusable If the post process can be reused on the same frame. (default: false)
  72703. * @param textureType Type of textures used when performing the post process. (default: 0)
  72704. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  72705. */
  72706. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  72707. if (imageToBlur === void 0) { imageToBlur = null; }
  72708. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  72709. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72710. if (blockCompilation === void 0) { blockCompilation = false; }
  72711. var _this = _super.call(this, name, direction, kernel, options, camera, samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, "#define DOF 1\r\n", blockCompilation) || this;
  72712. _this.direction = direction;
  72713. _this.onApplyObservable.add(function (effect) {
  72714. if (imageToBlur != null) {
  72715. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  72716. }
  72717. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  72718. if (scene.activeCamera) {
  72719. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  72720. }
  72721. });
  72722. return _this;
  72723. }
  72724. return DepthOfFieldBlurPostProcess;
  72725. }(BABYLON.BlurPostProcess));
  72726. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  72727. })(BABYLON || (BABYLON = {}));
  72728. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  72729. "use strict";
  72730. var BABYLON;
  72731. (function (BABYLON) {
  72732. /**
  72733. * Options to be set when merging outputs from the default pipeline.
  72734. */
  72735. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  72736. function DepthOfFieldMergePostProcessOptions() {
  72737. }
  72738. return DepthOfFieldMergePostProcessOptions;
  72739. }());
  72740. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  72741. /**
  72742. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  72743. */
  72744. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  72745. __extends(DepthOfFieldMergePostProcess, _super);
  72746. /**
  72747. * Creates a new instance of DepthOfFieldMergePostProcess
  72748. * @param name The name of the effect.
  72749. * @param originalFromInput Post process which's input will be used for the merge.
  72750. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  72751. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  72752. * @param options The required width/height ratio to downsize to before computing the render pass.
  72753. * @param camera The camera to apply the render pass to.
  72754. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  72755. * @param engine The engine which the post process will be applied. (default: current engine)
  72756. * @param reusable If the post process can be reused on the same frame. (default: false)
  72757. * @param textureType Type of textures used when performing the post process. (default: 0)
  72758. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  72759. */
  72760. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  72761. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72762. if (blockCompilation === void 0) { blockCompilation = false; }
  72763. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  72764. _this.blurSteps = blurSteps;
  72765. _this.onApplyObservable.add(function (effect) {
  72766. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  72767. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  72768. blurSteps.forEach(function (step, index) {
  72769. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  72770. });
  72771. });
  72772. if (!blockCompilation) {
  72773. _this.updateEffect();
  72774. }
  72775. return _this;
  72776. }
  72777. /**
  72778. * Updates the effect with the current post process compile time values and recompiles the shader.
  72779. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  72780. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  72781. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  72782. * @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
  72783. * @param onCompiled Called when the shader has been compiled.
  72784. * @param onError Called if there is an error when compiling a shader.
  72785. */
  72786. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  72787. if (defines === void 0) { defines = null; }
  72788. if (uniforms === void 0) { uniforms = null; }
  72789. if (samplers === void 0) { samplers = null; }
  72790. if (!defines) {
  72791. defines = "";
  72792. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  72793. }
  72794. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  72795. };
  72796. return DepthOfFieldMergePostProcess;
  72797. }(BABYLON.PostProcess));
  72798. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  72799. })(BABYLON || (BABYLON = {}));
  72800. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  72801. "use strict";
  72802. var BABYLON;
  72803. (function (BABYLON) {
  72804. /**
  72805. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  72806. */
  72807. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  72808. __extends(CircleOfConfusionPostProcess, _super);
  72809. /**
  72810. * Creates a new instance CircleOfConfusionPostProcess
  72811. * @param name The name of the effect.
  72812. * @param depthTexture The depth texture of the scene to compute the circle of confusion. This must be set in order for this to function but may be set after initialization if needed.
  72813. * @param options The required width/height ratio to downsize to before computing the render pass.
  72814. * @param camera The camera to apply the render pass to.
  72815. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  72816. * @param engine The engine which the post process will be applied. (default: current engine)
  72817. * @param reusable If the post process can be reused on the same frame. (default: false)
  72818. * @param textureType Type of textures used when performing the post process. (default: 0)
  72819. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  72820. */
  72821. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  72822. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72823. if (blockCompilation === void 0) { blockCompilation = false; }
  72824. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  72825. /**
  72826. * 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.
  72827. */
  72828. _this.lensSize = 50;
  72829. /**
  72830. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  72831. */
  72832. _this.fStop = 1.4;
  72833. /**
  72834. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  72835. */
  72836. _this.focusDistance = 2000;
  72837. /**
  72838. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  72839. */
  72840. _this.focalLength = 50;
  72841. _this._depthTexture = null;
  72842. _this._depthTexture = depthTexture;
  72843. _this.onApplyObservable.add(function (effect) {
  72844. if (!_this._depthTexture) {
  72845. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  72846. return;
  72847. }
  72848. effect.setTexture("depthSampler", _this._depthTexture);
  72849. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  72850. var aperture = _this.lensSize / _this.fStop;
  72851. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  72852. effect.setFloat('focusDistance', _this.focusDistance);
  72853. effect.setFloat('cocPrecalculation', cocPrecalculation);
  72854. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  72855. });
  72856. return _this;
  72857. }
  72858. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  72859. /**
  72860. * Depth texture to be used to compute the circle of confusion. This must be set here or in the constructor in order for the post process to function.
  72861. */
  72862. set: function (value) {
  72863. this._depthTexture = value;
  72864. },
  72865. enumerable: true,
  72866. configurable: true
  72867. });
  72868. return CircleOfConfusionPostProcess;
  72869. }(BABYLON.PostProcess));
  72870. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  72871. })(BABYLON || (BABYLON = {}));
  72872. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  72873. "use strict";
  72874. var BABYLON;
  72875. (function (BABYLON) {
  72876. /**
  72877. * Specifies the level of max blur that should be applied when using the depth of field effect
  72878. */
  72879. var DepthOfFieldEffectBlurLevel;
  72880. (function (DepthOfFieldEffectBlurLevel) {
  72881. /**
  72882. * Subtle blur
  72883. */
  72884. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  72885. /**
  72886. * Medium blur
  72887. */
  72888. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  72889. /**
  72890. * Large blur
  72891. */
  72892. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  72893. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  72894. ;
  72895. /**
  72896. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  72897. */
  72898. var DepthOfFieldEffect = /** @class */ (function (_super) {
  72899. __extends(DepthOfFieldEffect, _super);
  72900. /**
  72901. * Creates a new instance DepthOfFieldEffect
  72902. * @param scene The scene the effect belongs to.
  72903. * @param depthTexture The depth texture of the scene to compute the circle of confusion.This must be set in order for this to function but may be set after initialization if needed.
  72904. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  72905. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  72906. */
  72907. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  72908. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  72909. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  72910. if (blockCompilation === void 0) { blockCompilation = false; }
  72911. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  72912. return _this._effects;
  72913. }, true) || this;
  72914. /**
  72915. * Internal post processes in depth of field effect
  72916. */
  72917. _this._effects = [];
  72918. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  72919. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  72920. // 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)
  72921. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  72922. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  72923. _this._depthOfFieldBlurY = [];
  72924. _this._depthOfFieldBlurX = [];
  72925. var blurCount = 1;
  72926. var kernelSize = 15;
  72927. switch (blurLevel) {
  72928. case DepthOfFieldEffectBlurLevel.High: {
  72929. blurCount = 3;
  72930. kernelSize = 51;
  72931. break;
  72932. }
  72933. case DepthOfFieldEffectBlurLevel.Medium: {
  72934. blurCount = 2;
  72935. kernelSize = 31;
  72936. break;
  72937. }
  72938. default: {
  72939. kernelSize = 15;
  72940. blurCount = 1;
  72941. break;
  72942. }
  72943. }
  72944. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  72945. var ratio = 1.0;
  72946. for (var i = 0; i < blurCount; i++) {
  72947. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, ratio, null, _this._circleOfConfusion, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  72948. blurY.autoClear = false;
  72949. ratio = 0.75 / Math.pow(2, i);
  72950. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, ratio, null, _this._circleOfConfusion, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  72951. blurX.autoClear = false;
  72952. _this._depthOfFieldBlurY.push(blurY);
  72953. _this._depthOfFieldBlurX.push(blurX);
  72954. }
  72955. // Set all post processes on the effect.
  72956. _this._effects = [_this._circleOfConfusion];
  72957. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  72958. _this._effects.push(_this._depthOfFieldBlurY[i]);
  72959. _this._effects.push(_this._depthOfFieldBlurX[i]);
  72960. }
  72961. // Merge blurred images with original image based on circleOfConfusion
  72962. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  72963. _this._dofMerge.autoClear = false;
  72964. _this._effects.push(_this._dofMerge);
  72965. return _this;
  72966. }
  72967. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  72968. get: function () {
  72969. return this._circleOfConfusion.focalLength;
  72970. },
  72971. /**
  72972. * The focal the length of the camera used in the effect
  72973. */
  72974. set: function (value) {
  72975. this._circleOfConfusion.focalLength = value;
  72976. },
  72977. enumerable: true,
  72978. configurable: true
  72979. });
  72980. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  72981. get: function () {
  72982. return this._circleOfConfusion.fStop;
  72983. },
  72984. /**
  72985. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  72986. */
  72987. set: function (value) {
  72988. this._circleOfConfusion.fStop = value;
  72989. },
  72990. enumerable: true,
  72991. configurable: true
  72992. });
  72993. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  72994. get: function () {
  72995. return this._circleOfConfusion.focusDistance;
  72996. },
  72997. /**
  72998. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  72999. */
  73000. set: function (value) {
  73001. this._circleOfConfusion.focusDistance = value;
  73002. },
  73003. enumerable: true,
  73004. configurable: true
  73005. });
  73006. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  73007. get: function () {
  73008. return this._circleOfConfusion.lensSize;
  73009. },
  73010. /**
  73011. * 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.
  73012. */
  73013. set: function (value) {
  73014. this._circleOfConfusion.lensSize = value;
  73015. },
  73016. enumerable: true,
  73017. configurable: true
  73018. });
  73019. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  73020. /**
  73021. * Depth texture to be used to compute the circle of confusion. This must be set here or in the constructor in order for the post process to function.
  73022. */
  73023. set: function (value) {
  73024. this._circleOfConfusion.depthTexture = value;
  73025. },
  73026. enumerable: true,
  73027. configurable: true
  73028. });
  73029. /**
  73030. * Disposes each of the internal effects for a given camera.
  73031. * @param camera The camera to dispose the effect on.
  73032. */
  73033. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  73034. for (var effect in this._effects) {
  73035. this._effects[effect].dispose(camera);
  73036. }
  73037. };
  73038. /**
  73039. * Internal
  73040. */
  73041. DepthOfFieldEffect.prototype._updateEffects = function () {
  73042. for (var effect in this._effects) {
  73043. this._effects[effect].updateEffect();
  73044. }
  73045. };
  73046. /**
  73047. * Internal
  73048. * @returns if all the contained post processes are ready.
  73049. */
  73050. DepthOfFieldEffect.prototype._isReady = function () {
  73051. for (var effect in this._effects) {
  73052. if (!this._effects[effect].isReady()) {
  73053. return false;
  73054. }
  73055. }
  73056. return true;
  73057. };
  73058. return DepthOfFieldEffect;
  73059. }(BABYLON.PostProcessRenderEffect));
  73060. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  73061. })(BABYLON || (BABYLON = {}));
  73062. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  73063. "use strict";
  73064. var BABYLON;
  73065. (function (BABYLON) {
  73066. /**
  73067. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  73068. */
  73069. var BloomMergePostProcess = /** @class */ (function (_super) {
  73070. __extends(BloomMergePostProcess, _super);
  73071. /**
  73072. * Creates a new instance of @see BloomMergePostProcess
  73073. * @param name The name of the effect.
  73074. * @param originalFromInput Post process which's input will be used for the merge.
  73075. * @param blurred Blurred highlights post process which's output will be used.
  73076. * @param weight Weight of the bloom to be added to the original input.
  73077. * @param options The required width/height ratio to downsize to before computing the render pass.
  73078. * @param camera The camera to apply the render pass to.
  73079. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73080. * @param engine The engine which the post process will be applied. (default: current engine)
  73081. * @param reusable If the post process can be reused on the same frame. (default: false)
  73082. * @param textureType Type of textures used when performing the post process. (default: 0)
  73083. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  73084. */
  73085. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73086. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73087. if (blockCompilation === void 0) { blockCompilation = false; }
  73088. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  73089. _this.weight = weight;
  73090. _this.onApplyObservable.add(function (effect) {
  73091. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  73092. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  73093. effect.setFloat("bloomWeight", _this.weight);
  73094. });
  73095. if (!blockCompilation) {
  73096. _this.updateEffect();
  73097. }
  73098. return _this;
  73099. }
  73100. return BloomMergePostProcess;
  73101. }(BABYLON.PostProcess));
  73102. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  73103. })(BABYLON || (BABYLON = {}));
  73104. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  73105. "use strict";
  73106. var BABYLON;
  73107. (function (BABYLON) {
  73108. /**
  73109. * The extract highlights post process sets all pixels to black except pixels above the specified luminance threshold. Used as the first step for a bloom effect.
  73110. */
  73111. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  73112. __extends(ExtractHighlightsPostProcess, _super);
  73113. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73114. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73115. if (blockCompilation === void 0) { blockCompilation = false; }
  73116. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  73117. /**
  73118. * The luminance threshold, pixels below this value will be set to black.
  73119. */
  73120. _this.threshold = 0.9;
  73121. /**
  73122. * Internal
  73123. */
  73124. _this._exposure = 1;
  73125. /**
  73126. * Post process which has the input texture to be used when performing highlight extraction
  73127. */
  73128. _this._inputPostProcess = null;
  73129. _this.onApplyObservable.add(function (effect) {
  73130. if (_this._inputPostProcess) {
  73131. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  73132. }
  73133. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  73134. effect.setFloat('exposure', _this._exposure);
  73135. });
  73136. return _this;
  73137. }
  73138. return ExtractHighlightsPostProcess;
  73139. }(BABYLON.PostProcess));
  73140. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  73141. })(BABYLON || (BABYLON = {}));
  73142. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  73143. "use strict";
  73144. var BABYLON;
  73145. (function (BABYLON) {
  73146. /**
  73147. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  73148. */
  73149. var BloomEffect = /** @class */ (function (_super) {
  73150. __extends(BloomEffect, _super);
  73151. /**
  73152. * Creates a new instance of @see BloomEffect
  73153. * @param scene The scene the effect belongs to.
  73154. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  73155. * @param bloomKernel The size of the kernel to be used when applying the blur.
  73156. * @param bloomWeight The the strength of bloom.
  73157. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  73158. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  73159. */
  73160. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  73161. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  73162. if (blockCompilation === void 0) { blockCompilation = false; }
  73163. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  73164. return _this._effects;
  73165. }, true) || this;
  73166. _this.bloomScale = bloomScale;
  73167. /**
  73168. * Internal
  73169. */
  73170. _this._effects = [];
  73171. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  73172. _this._blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), 10.0, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, undefined, blockCompilation);
  73173. _this._blurX.alwaysForcePOT = true;
  73174. _this._blurX.autoClear = false;
  73175. _this._blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), 10.0, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, undefined, blockCompilation);
  73176. _this._blurY.alwaysForcePOT = true;
  73177. _this._blurY.autoClear = false;
  73178. _this.kernel = bloomKernel;
  73179. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  73180. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  73181. _this._merge.autoClear = false;
  73182. _this._effects.push(_this._merge);
  73183. return _this;
  73184. }
  73185. Object.defineProperty(BloomEffect.prototype, "threshold", {
  73186. /**
  73187. * The luminance threshold to find bright areas of the image to bloom.
  73188. */
  73189. get: function () {
  73190. return this._downscale.threshold;
  73191. },
  73192. set: function (value) {
  73193. this._downscale.threshold = value;
  73194. },
  73195. enumerable: true,
  73196. configurable: true
  73197. });
  73198. Object.defineProperty(BloomEffect.prototype, "weight", {
  73199. /**
  73200. * The strength of the bloom.
  73201. */
  73202. get: function () {
  73203. return this._merge.weight;
  73204. },
  73205. set: function (value) {
  73206. this._merge.weight = value;
  73207. },
  73208. enumerable: true,
  73209. configurable: true
  73210. });
  73211. Object.defineProperty(BloomEffect.prototype, "kernel", {
  73212. /**
  73213. * Specifies the size of the bloom blur kernel, relative to the final output size
  73214. */
  73215. get: function () {
  73216. return this._blurX.kernel / this.bloomScale;
  73217. },
  73218. set: function (value) {
  73219. this._blurX.kernel = value * this.bloomScale;
  73220. this._blurY.kernel = value * this.bloomScale;
  73221. },
  73222. enumerable: true,
  73223. configurable: true
  73224. });
  73225. /**
  73226. * Disposes each of the internal effects for a given camera.
  73227. * @param camera The camera to dispose the effect on.
  73228. */
  73229. BloomEffect.prototype.disposeEffects = function (camera) {
  73230. for (var effect in this._effects) {
  73231. this._effects[effect].dispose(camera);
  73232. }
  73233. };
  73234. /**
  73235. * Internal
  73236. */
  73237. BloomEffect.prototype._updateEffects = function () {
  73238. for (var effect in this._effects) {
  73239. this._effects[effect].updateEffect();
  73240. }
  73241. };
  73242. /**
  73243. * Internal
  73244. * @returns if all the contained post processes are ready.
  73245. */
  73246. BloomEffect.prototype._isReady = function () {
  73247. for (var effect in this._effects) {
  73248. if (!this._effects[effect].isReady()) {
  73249. return false;
  73250. }
  73251. }
  73252. return true;
  73253. };
  73254. return BloomEffect;
  73255. }(BABYLON.PostProcessRenderEffect));
  73256. BABYLON.BloomEffect = BloomEffect;
  73257. })(BABYLON || (BABYLON = {}));
  73258. //# sourceMappingURL=babylon.bloomEffect.js.map
  73259. "use strict";
  73260. var BABYLON;
  73261. (function (BABYLON) {
  73262. /**
  73263. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  73264. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  73265. */
  73266. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  73267. __extends(DefaultRenderingPipeline, _super);
  73268. /**
  73269. * @constructor
  73270. * @param {string} name - The rendering pipeline name
  73271. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73272. * @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)
  73273. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73274. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  73275. */
  73276. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  73277. if (automaticBuild === void 0) { automaticBuild = true; }
  73278. var _this = _super.call(this, scene.getEngine(), name) || this;
  73279. _this._originalCameras = [];
  73280. /**
  73281. * ID of the sharpen post process,
  73282. */
  73283. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  73284. /**
  73285. * ID of the image processing post process;
  73286. */
  73287. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  73288. /**
  73289. * ID of the Fast Approximate Anti-Aliasing post process;
  73290. */
  73291. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  73292. /**
  73293. * ID of the chromatic aberration post process,
  73294. */
  73295. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  73296. /**
  73297. * ID of the grain post process
  73298. */
  73299. _this.GrainPostProcessId = "GrainPostProcessEffect";
  73300. /**
  73301. * Animations which can be used to tweak settings over a period of time
  73302. */
  73303. _this.animations = [];
  73304. _this._imageProcessingConfigurationObserver = null;
  73305. // Values
  73306. _this._sharpenEnabled = false;
  73307. _this._bloomEnabled = false;
  73308. _this._depthOfFieldEnabled = false;
  73309. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  73310. _this._fxaaEnabled = false;
  73311. _this._imageProcessingEnabled = true;
  73312. _this._bloomScale = 0.5;
  73313. _this._chromaticAberrationEnabled = false;
  73314. _this._grainEnabled = false;
  73315. _this._buildAllowed = true;
  73316. _this._resizeObserver = null;
  73317. _this._hardwareScaleLevel = 1.0;
  73318. _this._bloomKernel = 64;
  73319. /**
  73320. * Specifies the weight of the bloom in the final rendering
  73321. */
  73322. _this._bloomWeight = 0.15;
  73323. /**
  73324. * Specifies the luma threshold for the area that will be blurred by the bloom
  73325. */
  73326. _this._bloomThreshold = 0.9;
  73327. _this._samples = 1;
  73328. _this._hasCleared = false;
  73329. _this._prevPostProcess = null;
  73330. _this._prevPrevPostProcess = null;
  73331. _this._cameras = cameras || [];
  73332. _this._originalCameras = _this._cameras.slice();
  73333. _this._buildAllowed = automaticBuild;
  73334. // Initialize
  73335. _this._scene = scene;
  73336. var caps = _this._scene.getEngine().getCaps();
  73337. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  73338. // Misc
  73339. if (_this._hdr) {
  73340. if (caps.textureHalfFloatRender) {
  73341. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73342. }
  73343. else if (caps.textureFloatRender) {
  73344. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  73345. }
  73346. }
  73347. else {
  73348. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  73349. }
  73350. // Attach
  73351. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73352. var engine = _this._scene.getEngine();
  73353. // Create post processes before hand so they can be modified before enabled.
  73354. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  73355. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  73356. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  73357. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  73358. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  73359. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  73360. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  73361. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  73362. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  73363. _this._resizeObserver = engine.onResizeObservable.add(function () {
  73364. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  73365. _this.bloomKernel = _this.bloomKernel;
  73366. });
  73367. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  73368. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  73369. });
  73370. _this._buildPipeline();
  73371. return _this;
  73372. }
  73373. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  73374. get: function () {
  73375. return this._sharpenEnabled;
  73376. },
  73377. /**
  73378. * Enable or disable the sharpen process from the pipeline
  73379. */
  73380. set: function (enabled) {
  73381. if (this._sharpenEnabled === enabled) {
  73382. return;
  73383. }
  73384. this._sharpenEnabled = enabled;
  73385. this._buildPipeline();
  73386. },
  73387. enumerable: true,
  73388. configurable: true
  73389. });
  73390. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  73391. /**
  73392. * Specifies the size of the bloom blur kernel, relative to the final output size
  73393. */
  73394. get: function () {
  73395. return this._bloomKernel;
  73396. },
  73397. set: function (value) {
  73398. this._bloomKernel = value;
  73399. this.bloom.kernel = value / this._hardwareScaleLevel;
  73400. },
  73401. enumerable: true,
  73402. configurable: true
  73403. });
  73404. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  73405. get: function () {
  73406. return this._bloomWeight;
  73407. },
  73408. /**
  73409. * The strength of the bloom.
  73410. */
  73411. set: function (value) {
  73412. if (this._bloomWeight === value) {
  73413. return;
  73414. }
  73415. this.bloom.weight = value;
  73416. this._bloomWeight = value;
  73417. },
  73418. enumerable: true,
  73419. configurable: true
  73420. });
  73421. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  73422. get: function () {
  73423. return this._bloomThreshold;
  73424. },
  73425. /**
  73426. * The strength of the bloom.
  73427. */
  73428. set: function (value) {
  73429. if (this._bloomThreshold === value) {
  73430. return;
  73431. }
  73432. this.bloom.threshold = value;
  73433. this._bloomThreshold = value;
  73434. },
  73435. enumerable: true,
  73436. configurable: true
  73437. });
  73438. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  73439. get: function () {
  73440. return this._bloomScale;
  73441. },
  73442. /**
  73443. * The scale of the bloom, lower value will provide better performance.
  73444. */
  73445. set: function (value) {
  73446. if (this._bloomScale === value) {
  73447. return;
  73448. }
  73449. this._bloomScale = value;
  73450. // recreate bloom and dispose old as this setting is not dynamic
  73451. this._rebuildBloom();
  73452. this._buildPipeline();
  73453. },
  73454. enumerable: true,
  73455. configurable: true
  73456. });
  73457. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  73458. get: function () {
  73459. return this._bloomEnabled;
  73460. },
  73461. /**
  73462. * Enable or disable the bloom from the pipeline
  73463. */
  73464. set: function (enabled) {
  73465. if (this._bloomEnabled === enabled) {
  73466. return;
  73467. }
  73468. this._bloomEnabled = enabled;
  73469. this._buildPipeline();
  73470. },
  73471. enumerable: true,
  73472. configurable: true
  73473. });
  73474. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  73475. // recreate bloom and dispose old as this setting is not dynamic
  73476. var oldBloom = this.bloom;
  73477. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  73478. this.bloom.threshold = oldBloom.threshold;
  73479. for (var i = 0; i < this._cameras.length; i++) {
  73480. oldBloom.disposeEffects(this._cameras[i]);
  73481. }
  73482. };
  73483. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  73484. /**
  73485. * If the depth of field is enabled.
  73486. */
  73487. get: function () {
  73488. return this._depthOfFieldEnabled;
  73489. },
  73490. set: function (enabled) {
  73491. if (this._depthOfFieldEnabled === enabled) {
  73492. return;
  73493. }
  73494. this._depthOfFieldEnabled = enabled;
  73495. this._buildPipeline();
  73496. },
  73497. enumerable: true,
  73498. configurable: true
  73499. });
  73500. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  73501. /**
  73502. * Blur level of the depth of field effect. (Higher blur will effect performance)
  73503. */
  73504. get: function () {
  73505. return this._depthOfFieldBlurLevel;
  73506. },
  73507. set: function (value) {
  73508. if (this._depthOfFieldBlurLevel === value) {
  73509. return;
  73510. }
  73511. this._depthOfFieldBlurLevel = value;
  73512. // recreate dof and dispose old as this setting is not dynamic
  73513. var oldDof = this.depthOfField;
  73514. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  73515. this.depthOfField.focalLength = oldDof.focalLength;
  73516. this.depthOfField.focusDistance = oldDof.focusDistance;
  73517. this.depthOfField.fStop = oldDof.fStop;
  73518. this.depthOfField.lensSize = oldDof.lensSize;
  73519. for (var i = 0; i < this._cameras.length; i++) {
  73520. oldDof.disposeEffects(this._cameras[i]);
  73521. }
  73522. this._buildPipeline();
  73523. },
  73524. enumerable: true,
  73525. configurable: true
  73526. });
  73527. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  73528. get: function () {
  73529. return this._fxaaEnabled;
  73530. },
  73531. /**
  73532. * If the anti aliasing is enabled.
  73533. */
  73534. set: function (enabled) {
  73535. if (this._fxaaEnabled === enabled) {
  73536. return;
  73537. }
  73538. this._fxaaEnabled = enabled;
  73539. this._buildPipeline();
  73540. },
  73541. enumerable: true,
  73542. configurable: true
  73543. });
  73544. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  73545. get: function () {
  73546. return this._samples;
  73547. },
  73548. /**
  73549. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  73550. */
  73551. set: function (sampleCount) {
  73552. if (this._samples === sampleCount) {
  73553. return;
  73554. }
  73555. this._samples = sampleCount;
  73556. this._buildPipeline();
  73557. },
  73558. enumerable: true,
  73559. configurable: true
  73560. });
  73561. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  73562. get: function () {
  73563. return this._imageProcessingEnabled;
  73564. },
  73565. /**
  73566. * If image processing is enabled.
  73567. */
  73568. set: function (enabled) {
  73569. if (this._imageProcessingEnabled === enabled) {
  73570. return;
  73571. }
  73572. this._imageProcessingEnabled = enabled;
  73573. this._buildPipeline();
  73574. },
  73575. enumerable: true,
  73576. configurable: true
  73577. });
  73578. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  73579. get: function () {
  73580. return this._chromaticAberrationEnabled;
  73581. },
  73582. /**
  73583. * Enable or disable the chromaticAberration process from the pipeline
  73584. */
  73585. set: function (enabled) {
  73586. if (this._chromaticAberrationEnabled === enabled) {
  73587. return;
  73588. }
  73589. this._chromaticAberrationEnabled = enabled;
  73590. this._buildPipeline();
  73591. },
  73592. enumerable: true,
  73593. configurable: true
  73594. });
  73595. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  73596. get: function () {
  73597. return this._grainEnabled;
  73598. },
  73599. /**
  73600. * Enable or disable the grain process from the pipeline
  73601. */
  73602. set: function (enabled) {
  73603. if (this._grainEnabled === enabled) {
  73604. return;
  73605. }
  73606. this._grainEnabled = enabled;
  73607. this._buildPipeline();
  73608. },
  73609. enumerable: true,
  73610. configurable: true
  73611. });
  73612. /**
  73613. * Force the compilation of the entire pipeline.
  73614. */
  73615. DefaultRenderingPipeline.prototype.prepare = function () {
  73616. var previousState = this._buildAllowed;
  73617. this._buildAllowed = true;
  73618. this._buildPipeline();
  73619. this._buildAllowed = previousState;
  73620. };
  73621. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  73622. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  73623. if (this._hasCleared) {
  73624. postProcess.autoClear = false;
  73625. }
  73626. else {
  73627. postProcess.autoClear = true;
  73628. this._scene.autoClear = false;
  73629. this._hasCleared = true;
  73630. }
  73631. if (!skipTextureSharing) {
  73632. if (this._prevPrevPostProcess) {
  73633. postProcess.shareOutputWith(this._prevPrevPostProcess);
  73634. }
  73635. else {
  73636. postProcess.useOwnOutput();
  73637. }
  73638. if (this._prevPostProcess) {
  73639. this._prevPrevPostProcess = this._prevPostProcess;
  73640. }
  73641. this._prevPostProcess = postProcess;
  73642. }
  73643. };
  73644. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  73645. var _this = this;
  73646. if (!this._buildAllowed) {
  73647. return;
  73648. }
  73649. this._scene.autoClear = true;
  73650. var engine = this._scene.getEngine();
  73651. this._disposePostProcesses();
  73652. if (this._cameras !== null) {
  73653. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  73654. // get back cameras to be used to reattach pipeline
  73655. this._cameras = this._originalCameras.slice();
  73656. }
  73657. this._reset();
  73658. this._prevPostProcess = null;
  73659. this._prevPrevPostProcess = null;
  73660. this._hasCleared = false;
  73661. if (this.depthOfFieldEnabled) {
  73662. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  73663. this.depthOfField.depthTexture = depthTexture;
  73664. if (!this.depthOfField._isReady()) {
  73665. this.depthOfField._updateEffects();
  73666. }
  73667. this.addEffect(this.depthOfField);
  73668. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  73669. }
  73670. if (this.bloomEnabled) {
  73671. if (!this.bloom._isReady()) {
  73672. this.bloom._updateEffects();
  73673. }
  73674. this.addEffect(this.bloom);
  73675. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  73676. }
  73677. if (this._imageProcessingEnabled) {
  73678. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  73679. if (this._hdr) {
  73680. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  73681. this._setAutoClearAndTextureSharing(this.imageProcessing);
  73682. }
  73683. else {
  73684. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  73685. }
  73686. }
  73687. if (this.sharpenEnabled) {
  73688. if (!this.sharpen.isReady()) {
  73689. this.sharpen.updateEffect();
  73690. }
  73691. this.addEffect(this._sharpenEffect);
  73692. this._setAutoClearAndTextureSharing(this.sharpen);
  73693. }
  73694. if (this.grainEnabled) {
  73695. if (!this.grain.isReady()) {
  73696. this.grain.updateEffect();
  73697. }
  73698. this.addEffect(this._grainEffect);
  73699. this._setAutoClearAndTextureSharing(this.grain);
  73700. }
  73701. if (this.chromaticAberrationEnabled) {
  73702. if (!this.chromaticAberration.isReady()) {
  73703. this.chromaticAberration.updateEffect();
  73704. }
  73705. this.addEffect(this._chromaticAberrationEffect);
  73706. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  73707. }
  73708. if (this.fxaaEnabled) {
  73709. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  73710. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  73711. this._setAutoClearAndTextureSharing(this.fxaa, true);
  73712. }
  73713. if (this._cameras !== null) {
  73714. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  73715. }
  73716. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  73717. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  73718. }
  73719. };
  73720. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  73721. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  73722. for (var i = 0; i < this._cameras.length; i++) {
  73723. var camera = this._cameras[i];
  73724. if (this.imageProcessing) {
  73725. this.imageProcessing.dispose(camera);
  73726. }
  73727. if (this.fxaa) {
  73728. this.fxaa.dispose(camera);
  73729. }
  73730. // These are created in the constructor and should not be disposed on every pipeline change
  73731. if (disposeNonRecreated) {
  73732. if (this.sharpen) {
  73733. this.sharpen.dispose(camera);
  73734. }
  73735. if (this.depthOfField) {
  73736. this.depthOfField.disposeEffects(camera);
  73737. }
  73738. if (this.bloom) {
  73739. this.bloom.disposeEffects(camera);
  73740. }
  73741. if (this.chromaticAberration) {
  73742. this.chromaticAberration.dispose(camera);
  73743. }
  73744. if (this.grain) {
  73745. this.grain.dispose(camera);
  73746. }
  73747. }
  73748. }
  73749. this.imageProcessing = null;
  73750. this.fxaa = null;
  73751. if (disposeNonRecreated) {
  73752. this.sharpen = null;
  73753. this._sharpenEffect = null;
  73754. this.depthOfField = null;
  73755. this.bloom = null;
  73756. this.chromaticAberration = null;
  73757. this._chromaticAberrationEffect = null;
  73758. this.grain = null;
  73759. this._grainEffect = null;
  73760. }
  73761. };
  73762. /**
  73763. * Dispose of the pipeline and stop all post processes
  73764. */
  73765. DefaultRenderingPipeline.prototype.dispose = function () {
  73766. this._disposePostProcesses(true);
  73767. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  73768. this._scene.autoClear = true;
  73769. if (this._resizeObserver) {
  73770. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  73771. this._resizeObserver = null;
  73772. }
  73773. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  73774. _super.prototype.dispose.call(this);
  73775. };
  73776. /**
  73777. * Serialize the rendering pipeline (Used when exporting)
  73778. * @returns the serialized object
  73779. */
  73780. DefaultRenderingPipeline.prototype.serialize = function () {
  73781. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  73782. serializationObject.customType = "DefaultRenderingPipeline";
  73783. return serializationObject;
  73784. };
  73785. /**
  73786. * Parse the serialized pipeline
  73787. * @param source Source pipeline.
  73788. * @param scene The scene to load the pipeline to.
  73789. * @param rootUrl The URL of the serialized pipeline.
  73790. * @returns An instantiated pipeline from the serialized object.
  73791. */
  73792. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  73793. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  73794. };
  73795. __decorate([
  73796. BABYLON.serialize()
  73797. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  73798. __decorate([
  73799. BABYLON.serialize()
  73800. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  73801. __decorate([
  73802. BABYLON.serialize()
  73803. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  73804. __decorate([
  73805. BABYLON.serialize()
  73806. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  73807. __decorate([
  73808. BABYLON.serialize()
  73809. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  73810. __decorate([
  73811. BABYLON.serialize()
  73812. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  73813. __decorate([
  73814. BABYLON.serialize()
  73815. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  73816. __decorate([
  73817. BABYLON.serialize()
  73818. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  73819. __decorate([
  73820. BABYLON.serialize()
  73821. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  73822. __decorate([
  73823. BABYLON.serialize()
  73824. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  73825. __decorate([
  73826. BABYLON.serialize()
  73827. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  73828. __decorate([
  73829. BABYLON.serialize()
  73830. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  73831. __decorate([
  73832. BABYLON.serialize()
  73833. ], DefaultRenderingPipeline.prototype, "samples", null);
  73834. __decorate([
  73835. BABYLON.serialize()
  73836. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  73837. __decorate([
  73838. BABYLON.serialize()
  73839. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  73840. __decorate([
  73841. BABYLON.serialize()
  73842. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  73843. return DefaultRenderingPipeline;
  73844. }(BABYLON.PostProcessRenderPipeline));
  73845. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  73846. })(BABYLON || (BABYLON = {}));
  73847. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  73848. "use strict";
  73849. var BABYLON;
  73850. (function (BABYLON) {
  73851. /**
  73852. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  73853. */
  73854. var GeometryBufferRenderer = /** @class */ (function () {
  73855. /**
  73856. * Creates a new G Buffer for the scene
  73857. * @param scene The scene the buffer belongs to
  73858. * @param ratio How big is the buffer related to the main canvas.
  73859. */
  73860. function GeometryBufferRenderer(scene, ratio) {
  73861. if (ratio === void 0) { ratio = 1; }
  73862. this._enablePosition = false;
  73863. this._scene = scene;
  73864. this._ratio = ratio;
  73865. // Render target
  73866. this._createRenderTargets();
  73867. }
  73868. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  73869. /**
  73870. * Set the render list (meshes to be rendered) used in the G buffer.
  73871. */
  73872. set: function (meshes) {
  73873. this._multiRenderTarget.renderList = meshes;
  73874. },
  73875. enumerable: true,
  73876. configurable: true
  73877. });
  73878. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  73879. /**
  73880. * Gets wether or not G buffer are supported by the running hardware.
  73881. * This requires draw buffer supports
  73882. */
  73883. get: function () {
  73884. return this._multiRenderTarget.isSupported;
  73885. },
  73886. enumerable: true,
  73887. configurable: true
  73888. });
  73889. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  73890. /**
  73891. * Gets wether or not position are enabled for the G buffer.
  73892. */
  73893. get: function () {
  73894. return this._enablePosition;
  73895. },
  73896. /**
  73897. * Sets wether or not position are enabled for the G buffer.
  73898. */
  73899. set: function (enable) {
  73900. this._enablePosition = enable;
  73901. this.dispose();
  73902. this._createRenderTargets();
  73903. },
  73904. enumerable: true,
  73905. configurable: true
  73906. });
  73907. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  73908. /**
  73909. * Gets the scene associated with the buffer.
  73910. */
  73911. get: function () {
  73912. return this._scene;
  73913. },
  73914. enumerable: true,
  73915. configurable: true
  73916. });
  73917. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  73918. /**
  73919. * Gets the ratio used by the buffer during its creation.
  73920. * How big is the buffer related to the main canvas.
  73921. */
  73922. get: function () {
  73923. return this._ratio;
  73924. },
  73925. enumerable: true,
  73926. configurable: true
  73927. });
  73928. /**
  73929. * Checks wether everything is ready to render a submesh to the G buffer.
  73930. * @param subMesh the submesh to check readiness for
  73931. * @param useInstances is the mesh drawn using instance or not
  73932. * @returns true if ready otherwise false
  73933. */
  73934. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  73935. var material = subMesh.getMaterial();
  73936. if (material && material.disableDepthWrite) {
  73937. return false;
  73938. }
  73939. var defines = [];
  73940. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  73941. var mesh = subMesh.getMesh();
  73942. // Alpha test
  73943. if (material && material.needAlphaTesting()) {
  73944. defines.push("#define ALPHATEST");
  73945. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73946. attribs.push(BABYLON.VertexBuffer.UVKind);
  73947. defines.push("#define UV1");
  73948. }
  73949. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  73950. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  73951. defines.push("#define UV2");
  73952. }
  73953. }
  73954. // Buffers
  73955. if (this._enablePosition) {
  73956. defines.push("#define POSITION");
  73957. }
  73958. // Bones
  73959. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73960. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73961. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73962. if (mesh.numBoneInfluencers > 4) {
  73963. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73964. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73965. }
  73966. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73967. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  73968. }
  73969. else {
  73970. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73971. }
  73972. // Instances
  73973. if (useInstances) {
  73974. defines.push("#define INSTANCES");
  73975. attribs.push("world0");
  73976. attribs.push("world1");
  73977. attribs.push("world2");
  73978. attribs.push("world3");
  73979. }
  73980. // Get correct effect
  73981. var join = defines.join("\n");
  73982. if (this._cachedDefines !== join) {
  73983. this._cachedDefines = join;
  73984. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  73985. }
  73986. return this._effect.isReady();
  73987. };
  73988. /**
  73989. * Gets the current underlying G Buffer.
  73990. * @returns the buffer
  73991. */
  73992. GeometryBufferRenderer.prototype.getGBuffer = function () {
  73993. return this._multiRenderTarget;
  73994. };
  73995. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  73996. /**
  73997. * Gets the number of samples used to render the buffer (anti aliasing).
  73998. */
  73999. get: function () {
  74000. return this._multiRenderTarget.samples;
  74001. },
  74002. /**
  74003. * Sets the number of samples used to render the buffer (anti aliasing).
  74004. */
  74005. set: function (value) {
  74006. this._multiRenderTarget.samples = value;
  74007. },
  74008. enumerable: true,
  74009. configurable: true
  74010. });
  74011. /**
  74012. * Disposes the renderer and frees up associated resources.
  74013. */
  74014. GeometryBufferRenderer.prototype.dispose = function () {
  74015. this.getGBuffer().dispose();
  74016. };
  74017. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  74018. var _this = this;
  74019. var engine = this._scene.getEngine();
  74020. var count = this._enablePosition ? 3 : 2;
  74021. 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 });
  74022. if (!this.isSupported) {
  74023. return;
  74024. }
  74025. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74026. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74027. this._multiRenderTarget.refreshRate = 1;
  74028. this._multiRenderTarget.renderParticles = false;
  74029. this._multiRenderTarget.renderList = null;
  74030. // set default depth value to 1.0 (far away)
  74031. this._multiRenderTarget.onClearObservable.add(function (engine) {
  74032. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  74033. });
  74034. // Custom render function
  74035. var renderSubMesh = function (subMesh) {
  74036. var mesh = subMesh.getRenderingMesh();
  74037. var scene = _this._scene;
  74038. var engine = scene.getEngine();
  74039. var material = subMesh.getMaterial();
  74040. if (!material) {
  74041. return;
  74042. }
  74043. // Culling
  74044. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  74045. // Managing instances
  74046. var batch = mesh._getInstancesRenderList(subMesh._id);
  74047. if (batch.mustReturn) {
  74048. return;
  74049. }
  74050. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  74051. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  74052. engine.enableEffect(_this._effect);
  74053. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  74054. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  74055. _this._effect.setMatrix("view", scene.getViewMatrix());
  74056. // Alpha test
  74057. if (material && material.needAlphaTesting()) {
  74058. var alphaTexture = material.getAlphaTestTexture();
  74059. if (alphaTexture) {
  74060. _this._effect.setTexture("diffuseSampler", alphaTexture);
  74061. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  74062. }
  74063. }
  74064. // Bones
  74065. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  74066. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  74067. }
  74068. // Draw
  74069. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  74070. }
  74071. };
  74072. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  74073. var index;
  74074. if (depthOnlySubMeshes.length) {
  74075. engine.setColorWrite(false);
  74076. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  74077. renderSubMesh(depthOnlySubMeshes.data[index]);
  74078. }
  74079. engine.setColorWrite(true);
  74080. }
  74081. for (index = 0; index < opaqueSubMeshes.length; index++) {
  74082. renderSubMesh(opaqueSubMeshes.data[index]);
  74083. }
  74084. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  74085. renderSubMesh(alphaTestSubMeshes.data[index]);
  74086. }
  74087. };
  74088. };
  74089. return GeometryBufferRenderer;
  74090. }());
  74091. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  74092. })(BABYLON || (BABYLON = {}));
  74093. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  74094. "use strict";
  74095. var BABYLON;
  74096. (function (BABYLON) {
  74097. var RefractionPostProcess = /** @class */ (function (_super) {
  74098. __extends(RefractionPostProcess, _super);
  74099. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  74100. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  74101. _this.color = color;
  74102. _this.depth = depth;
  74103. _this.colorLevel = colorLevel;
  74104. _this._ownRefractionTexture = true;
  74105. _this.onActivateObservable.add(function (cam) {
  74106. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  74107. });
  74108. _this.onApplyObservable.add(function (effect) {
  74109. effect.setColor3("baseColor", _this.color);
  74110. effect.setFloat("depth", _this.depth);
  74111. effect.setFloat("colorLevel", _this.colorLevel);
  74112. effect.setTexture("refractionSampler", _this._refTexture);
  74113. });
  74114. return _this;
  74115. }
  74116. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  74117. /**
  74118. * Gets or sets the refraction texture
  74119. * Please note that you are responsible for disposing the texture if you set it manually
  74120. */
  74121. get: function () {
  74122. return this._refTexture;
  74123. },
  74124. set: function (value) {
  74125. if (this._refTexture && this._ownRefractionTexture) {
  74126. this._refTexture.dispose();
  74127. }
  74128. this._refTexture = value;
  74129. this._ownRefractionTexture = false;
  74130. },
  74131. enumerable: true,
  74132. configurable: true
  74133. });
  74134. // Methods
  74135. RefractionPostProcess.prototype.dispose = function (camera) {
  74136. if (this._refTexture && this._ownRefractionTexture) {
  74137. this._refTexture.dispose();
  74138. this._refTexture = null;
  74139. }
  74140. _super.prototype.dispose.call(this, camera);
  74141. };
  74142. return RefractionPostProcess;
  74143. }(BABYLON.PostProcess));
  74144. BABYLON.RefractionPostProcess = RefractionPostProcess;
  74145. })(BABYLON || (BABYLON = {}));
  74146. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  74147. "use strict";
  74148. var BABYLON;
  74149. (function (BABYLON) {
  74150. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  74151. __extends(BlackAndWhitePostProcess, _super);
  74152. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  74153. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  74154. _this.degree = 1;
  74155. _this.onApplyObservable.add(function (effect) {
  74156. effect.setFloat("degree", _this.degree);
  74157. });
  74158. return _this;
  74159. }
  74160. return BlackAndWhitePostProcess;
  74161. }(BABYLON.PostProcess));
  74162. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  74163. })(BABYLON || (BABYLON = {}));
  74164. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  74165. "use strict";
  74166. var BABYLON;
  74167. (function (BABYLON) {
  74168. /**
  74169. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  74170. * input texture to perform effects such as edge detection or sharpening
  74171. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  74172. */
  74173. var ConvolutionPostProcess = /** @class */ (function (_super) {
  74174. __extends(ConvolutionPostProcess, _super);
  74175. /**
  74176. * Creates a new instance ConvolutionPostProcess
  74177. * @param name The name of the effect.
  74178. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  74179. * @param options The required width/height ratio to downsize to before computing the render pass.
  74180. * @param camera The camera to apply the render pass to.
  74181. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74182. * @param engine The engine which the post process will be applied. (default: current engine)
  74183. * @param reusable If the post process can be reused on the same frame. (default: false)
  74184. * @param textureType Type of textures used when performing the post process. (default: 0)
  74185. */
  74186. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  74187. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74188. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  74189. _this.kernel = kernel;
  74190. _this.onApply = function (effect) {
  74191. effect.setFloat2("screenSize", _this.width, _this.height);
  74192. effect.setArray("kernel", _this.kernel);
  74193. };
  74194. return _this;
  74195. }
  74196. // Statics
  74197. /**
  74198. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  74199. */
  74200. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  74201. /**
  74202. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  74203. */
  74204. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  74205. /**
  74206. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  74207. */
  74208. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  74209. /**
  74210. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  74211. */
  74212. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  74213. /**
  74214. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  74215. */
  74216. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  74217. /**
  74218. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  74219. */
  74220. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  74221. return ConvolutionPostProcess;
  74222. }(BABYLON.PostProcess));
  74223. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  74224. })(BABYLON || (BABYLON = {}));
  74225. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  74226. "use strict";
  74227. var BABYLON;
  74228. (function (BABYLON) {
  74229. var FilterPostProcess = /** @class */ (function (_super) {
  74230. __extends(FilterPostProcess, _super);
  74231. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  74232. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  74233. _this.kernelMatrix = kernelMatrix;
  74234. _this.onApply = function (effect) {
  74235. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  74236. };
  74237. return _this;
  74238. }
  74239. return FilterPostProcess;
  74240. }(BABYLON.PostProcess));
  74241. BABYLON.FilterPostProcess = FilterPostProcess;
  74242. })(BABYLON || (BABYLON = {}));
  74243. //# sourceMappingURL=babylon.filterPostProcess.js.map
  74244. "use strict";
  74245. var BABYLON;
  74246. (function (BABYLON) {
  74247. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  74248. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  74249. __extends(VolumetricLightScatteringPostProcess, _super);
  74250. /**
  74251. * @constructor
  74252. * @param {string} name - The post-process name
  74253. * @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)
  74254. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  74255. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  74256. * @param {number} samples - The post-process quality, default 100
  74257. * @param {number} samplingMode - The post-process filtering mode
  74258. * @param {BABYLON.Engine} engine - The babylon engine
  74259. * @param {boolean} reusable - If the post-process is reusable
  74260. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  74261. */
  74262. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  74263. if (samples === void 0) { samples = 100; }
  74264. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74265. 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;
  74266. _this._screenCoordinates = BABYLON.Vector2.Zero();
  74267. /**
  74268. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  74269. */
  74270. _this.customMeshPosition = BABYLON.Vector3.Zero();
  74271. /**
  74272. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  74273. */
  74274. _this.useCustomMeshPosition = false;
  74275. /**
  74276. * If the post-process should inverse the light scattering direction
  74277. */
  74278. _this.invert = true;
  74279. /**
  74280. * Array containing the excluded meshes not rendered in the internal pass
  74281. */
  74282. _this.excludedMeshes = new Array();
  74283. /**
  74284. * Controls the overall intensity of the post-process
  74285. */
  74286. _this.exposure = 0.3;
  74287. /**
  74288. * Dissipates each sample's contribution in range [0, 1]
  74289. */
  74290. _this.decay = 0.96815;
  74291. /**
  74292. * Controls the overall intensity of each sample
  74293. */
  74294. _this.weight = 0.58767;
  74295. /**
  74296. * Controls the density of each sample
  74297. */
  74298. _this.density = 0.926;
  74299. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  74300. engine = scene.getEngine();
  74301. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  74302. // Configure mesh
  74303. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  74304. // Configure
  74305. _this._createPass(scene, ratio.passRatio || ratio);
  74306. _this.onActivate = function (camera) {
  74307. if (!_this.isSupported) {
  74308. _this.dispose(camera);
  74309. }
  74310. _this.onActivate = null;
  74311. };
  74312. _this.onApplyObservable.add(function (effect) {
  74313. _this._updateMeshScreenCoordinates(scene);
  74314. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  74315. effect.setFloat("exposure", _this.exposure);
  74316. effect.setFloat("decay", _this.decay);
  74317. effect.setFloat("weight", _this.weight);
  74318. effect.setFloat("density", _this.density);
  74319. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  74320. });
  74321. return _this;
  74322. }
  74323. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  74324. get: function () {
  74325. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  74326. return false;
  74327. },
  74328. set: function (useDiffuseColor) {
  74329. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  74330. },
  74331. enumerable: true,
  74332. configurable: true
  74333. });
  74334. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  74335. return "VolumetricLightScatteringPostProcess";
  74336. };
  74337. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  74338. var mesh = subMesh.getMesh();
  74339. // Render this.mesh as default
  74340. if (mesh === this.mesh && mesh.material) {
  74341. return mesh.material.isReady(mesh);
  74342. }
  74343. var defines = [];
  74344. var attribs = [BABYLON.VertexBuffer.PositionKind];
  74345. var material = subMesh.getMaterial();
  74346. // Alpha test
  74347. if (material) {
  74348. if (material.needAlphaTesting()) {
  74349. defines.push("#define ALPHATEST");
  74350. }
  74351. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  74352. attribs.push(BABYLON.VertexBuffer.UVKind);
  74353. defines.push("#define UV1");
  74354. }
  74355. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  74356. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  74357. defines.push("#define UV2");
  74358. }
  74359. }
  74360. // Bones
  74361. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  74362. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  74363. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  74364. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  74365. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  74366. }
  74367. else {
  74368. defines.push("#define NUM_BONE_INFLUENCERS 0");
  74369. }
  74370. // Instances
  74371. if (useInstances) {
  74372. defines.push("#define INSTANCES");
  74373. attribs.push("world0");
  74374. attribs.push("world1");
  74375. attribs.push("world2");
  74376. attribs.push("world3");
  74377. }
  74378. // Get correct effect
  74379. var join = defines.join("\n");
  74380. if (this._cachedDefines !== join) {
  74381. this._cachedDefines = join;
  74382. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  74383. }
  74384. return this._volumetricLightScatteringPass.isReady();
  74385. };
  74386. /**
  74387. * Sets the new light position for light scattering effect
  74388. * @param {BABYLON.Vector3} The new custom light position
  74389. */
  74390. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  74391. this.customMeshPosition = position;
  74392. };
  74393. /**
  74394. * Returns the light position for light scattering effect
  74395. * @return {BABYLON.Vector3} The custom light position
  74396. */
  74397. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  74398. return this.customMeshPosition;
  74399. };
  74400. /**
  74401. * Disposes the internal assets and detaches the post-process from the camera
  74402. */
  74403. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  74404. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  74405. if (rttIndex !== -1) {
  74406. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  74407. }
  74408. this._volumetricLightScatteringRTT.dispose();
  74409. _super.prototype.dispose.call(this, camera);
  74410. };
  74411. /**
  74412. * Returns the render target texture used by the post-process
  74413. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  74414. */
  74415. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  74416. return this._volumetricLightScatteringRTT;
  74417. };
  74418. // Private methods
  74419. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  74420. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  74421. return true;
  74422. }
  74423. return false;
  74424. };
  74425. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  74426. var _this = this;
  74427. var engine = scene.getEngine();
  74428. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  74429. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74430. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74431. this._volumetricLightScatteringRTT.renderList = null;
  74432. this._volumetricLightScatteringRTT.renderParticles = false;
  74433. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  74434. var camera = this.getCamera();
  74435. if (camera) {
  74436. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  74437. }
  74438. else {
  74439. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  74440. }
  74441. // Custom render function for submeshes
  74442. var renderSubMesh = function (subMesh) {
  74443. var mesh = subMesh.getRenderingMesh();
  74444. if (_this._meshExcluded(mesh)) {
  74445. return;
  74446. }
  74447. var material = subMesh.getMaterial();
  74448. if (!material) {
  74449. return;
  74450. }
  74451. var scene = mesh.getScene();
  74452. var engine = scene.getEngine();
  74453. // Culling
  74454. engine.setState(material.backFaceCulling);
  74455. // Managing instances
  74456. var batch = mesh._getInstancesRenderList(subMesh._id);
  74457. if (batch.mustReturn) {
  74458. return;
  74459. }
  74460. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  74461. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  74462. var effect = _this._volumetricLightScatteringPass;
  74463. if (mesh === _this.mesh) {
  74464. if (subMesh.effect) {
  74465. effect = subMesh.effect;
  74466. }
  74467. else {
  74468. effect = material.getEffect();
  74469. }
  74470. }
  74471. engine.enableEffect(effect);
  74472. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  74473. if (mesh === _this.mesh) {
  74474. material.bind(mesh.getWorldMatrix(), mesh);
  74475. }
  74476. else {
  74477. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  74478. // Alpha test
  74479. if (material && material.needAlphaTesting()) {
  74480. var alphaTexture = material.getAlphaTestTexture();
  74481. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  74482. if (alphaTexture) {
  74483. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  74484. }
  74485. }
  74486. // Bones
  74487. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  74488. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  74489. }
  74490. }
  74491. // Draw
  74492. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  74493. }
  74494. };
  74495. // Render target texture callbacks
  74496. var savedSceneClearColor;
  74497. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  74498. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  74499. savedSceneClearColor = scene.clearColor;
  74500. scene.clearColor = sceneClearColor;
  74501. });
  74502. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  74503. scene.clearColor = savedSceneClearColor;
  74504. });
  74505. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  74506. var engine = scene.getEngine();
  74507. var index;
  74508. if (depthOnlySubMeshes.length) {
  74509. engine.setColorWrite(false);
  74510. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  74511. renderSubMesh(depthOnlySubMeshes.data[index]);
  74512. }
  74513. engine.setColorWrite(true);
  74514. }
  74515. for (index = 0; index < opaqueSubMeshes.length; index++) {
  74516. renderSubMesh(opaqueSubMeshes.data[index]);
  74517. }
  74518. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  74519. renderSubMesh(alphaTestSubMeshes.data[index]);
  74520. }
  74521. if (transparentSubMeshes.length) {
  74522. // Sort sub meshes
  74523. for (index = 0; index < transparentSubMeshes.length; index++) {
  74524. var submesh = transparentSubMeshes.data[index];
  74525. var boundingInfo = submesh.getBoundingInfo();
  74526. if (boundingInfo && scene.activeCamera) {
  74527. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  74528. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  74529. }
  74530. }
  74531. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  74532. sortedArray.sort(function (a, b) {
  74533. // Alpha index first
  74534. if (a._alphaIndex > b._alphaIndex) {
  74535. return 1;
  74536. }
  74537. if (a._alphaIndex < b._alphaIndex) {
  74538. return -1;
  74539. }
  74540. // Then distance to camera
  74541. if (a._distanceToCamera < b._distanceToCamera) {
  74542. return 1;
  74543. }
  74544. if (a._distanceToCamera > b._distanceToCamera) {
  74545. return -1;
  74546. }
  74547. return 0;
  74548. });
  74549. // Render sub meshes
  74550. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  74551. for (index = 0; index < sortedArray.length; index++) {
  74552. renderSubMesh(sortedArray[index]);
  74553. }
  74554. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  74555. }
  74556. };
  74557. };
  74558. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  74559. var transform = scene.getTransformMatrix();
  74560. var meshPosition;
  74561. if (this.useCustomMeshPosition) {
  74562. meshPosition = this.customMeshPosition;
  74563. }
  74564. else if (this.attachedNode) {
  74565. meshPosition = this.attachedNode.position;
  74566. }
  74567. else {
  74568. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  74569. }
  74570. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  74571. this._screenCoordinates.x = pos.x / this._viewPort.width;
  74572. this._screenCoordinates.y = pos.y / this._viewPort.height;
  74573. if (this.invert)
  74574. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  74575. };
  74576. // Static methods
  74577. /**
  74578. * Creates a default mesh for the Volumeric Light Scattering post-process
  74579. * @param {string} The mesh name
  74580. * @param {BABYLON.Scene} The scene where to create the mesh
  74581. * @return {BABYLON.Mesh} the default mesh
  74582. */
  74583. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  74584. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  74585. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  74586. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  74587. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  74588. mesh.material = material;
  74589. return mesh;
  74590. };
  74591. __decorate([
  74592. BABYLON.serializeAsVector3()
  74593. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  74594. __decorate([
  74595. BABYLON.serialize()
  74596. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  74597. __decorate([
  74598. BABYLON.serialize()
  74599. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  74600. __decorate([
  74601. BABYLON.serializeAsMeshReference()
  74602. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  74603. __decorate([
  74604. BABYLON.serialize()
  74605. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  74606. __decorate([
  74607. BABYLON.serialize()
  74608. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  74609. __decorate([
  74610. BABYLON.serialize()
  74611. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  74612. __decorate([
  74613. BABYLON.serialize()
  74614. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  74615. __decorate([
  74616. BABYLON.serialize()
  74617. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  74618. return VolumetricLightScatteringPostProcess;
  74619. }(BABYLON.PostProcess));
  74620. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  74621. })(BABYLON || (BABYLON = {}));
  74622. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  74623. "use strict";
  74624. //
  74625. // This post-process allows the modification of rendered colors by using
  74626. // a 'look-up table' (LUT). This effect is also called Color Grading.
  74627. //
  74628. // The object needs to be provided an url to a texture containing the color
  74629. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  74630. // Use an image editing software to tweak the LUT to match your needs.
  74631. //
  74632. // For an example of a color LUT, see here:
  74633. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  74634. // For explanations on color grading, see here:
  74635. // http://udn.epicgames.com/Three/ColorGrading.html
  74636. //
  74637. var BABYLON;
  74638. (function (BABYLON) {
  74639. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  74640. __extends(ColorCorrectionPostProcess, _super);
  74641. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  74642. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  74643. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  74644. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  74645. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74646. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74647. _this.onApply = function (effect) {
  74648. effect.setTexture("colorTable", _this._colorTableTexture);
  74649. };
  74650. return _this;
  74651. }
  74652. return ColorCorrectionPostProcess;
  74653. }(BABYLON.PostProcess));
  74654. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  74655. })(BABYLON || (BABYLON = {}));
  74656. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  74657. "use strict";
  74658. var BABYLON;
  74659. (function (BABYLON) {
  74660. var TonemappingOperator;
  74661. (function (TonemappingOperator) {
  74662. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  74663. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  74664. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  74665. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  74666. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  74667. ;
  74668. var TonemapPostProcess = /** @class */ (function (_super) {
  74669. __extends(TonemapPostProcess, _super);
  74670. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  74671. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74672. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74673. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  74674. _this._operator = _operator;
  74675. _this.exposureAdjustment = exposureAdjustment;
  74676. var defines = "#define ";
  74677. if (_this._operator === TonemappingOperator.Hable)
  74678. defines += "HABLE_TONEMAPPING";
  74679. else if (_this._operator === TonemappingOperator.Reinhard)
  74680. defines += "REINHARD_TONEMAPPING";
  74681. else if (_this._operator === TonemappingOperator.HejiDawson)
  74682. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  74683. else if (_this._operator === TonemappingOperator.Photographic)
  74684. defines += "PHOTOGRAPHIC_TONEMAPPING";
  74685. //sadly a second call to create the effect.
  74686. _this.updateEffect(defines);
  74687. _this.onApply = function (effect) {
  74688. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  74689. };
  74690. return _this;
  74691. }
  74692. return TonemapPostProcess;
  74693. }(BABYLON.PostProcess));
  74694. BABYLON.TonemapPostProcess = TonemapPostProcess;
  74695. })(BABYLON || (BABYLON = {}));
  74696. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  74697. "use strict";
  74698. var BABYLON;
  74699. (function (BABYLON) {
  74700. var DisplayPassPostProcess = /** @class */ (function (_super) {
  74701. __extends(DisplayPassPostProcess, _super);
  74702. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  74703. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  74704. }
  74705. return DisplayPassPostProcess;
  74706. }(BABYLON.PostProcess));
  74707. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  74708. })(BABYLON || (BABYLON = {}));
  74709. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  74710. "use strict";
  74711. var BABYLON;
  74712. (function (BABYLON) {
  74713. var HighlightsPostProcess = /** @class */ (function (_super) {
  74714. __extends(HighlightsPostProcess, _super);
  74715. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  74716. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74717. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  74718. }
  74719. return HighlightsPostProcess;
  74720. }(BABYLON.PostProcess));
  74721. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  74722. })(BABYLON || (BABYLON = {}));
  74723. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  74724. "use strict";
  74725. var BABYLON;
  74726. (function (BABYLON) {
  74727. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  74728. __extends(ImageProcessingPostProcess, _super);
  74729. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  74730. if (camera === void 0) { camera = null; }
  74731. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74732. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  74733. _this._fromLinearSpace = true;
  74734. /**
  74735. * Defines cache preventing GC.
  74736. */
  74737. _this._defines = {
  74738. IMAGEPROCESSING: false,
  74739. VIGNETTE: false,
  74740. VIGNETTEBLENDMODEMULTIPLY: false,
  74741. VIGNETTEBLENDMODEOPAQUE: false,
  74742. TONEMAPPING: false,
  74743. CONTRAST: false,
  74744. COLORCURVES: false,
  74745. COLORGRADING: false,
  74746. COLORGRADING3D: false,
  74747. FROMLINEARSPACE: false,
  74748. SAMPLER3DGREENDEPTH: false,
  74749. SAMPLER3DBGRMAP: false,
  74750. IMAGEPROCESSINGPOSTPROCESS: false,
  74751. EXPOSURE: false,
  74752. };
  74753. // Setup the configuration as forced by the constructor. This would then not force the
  74754. // scene materials output in linear space and let untouched the default forward pass.
  74755. if (imageProcessingConfiguration) {
  74756. imageProcessingConfiguration.applyByPostProcess = true;
  74757. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  74758. // This will cause the shader to be compiled
  74759. _this.fromLinearSpace = false;
  74760. }
  74761. else {
  74762. _this._attachImageProcessingConfiguration(null, true);
  74763. _this.imageProcessingConfiguration.applyByPostProcess = true;
  74764. }
  74765. _this.onApply = function (effect) {
  74766. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  74767. };
  74768. return _this;
  74769. }
  74770. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  74771. /**
  74772. * Gets the image processing configuration used either in this material.
  74773. */
  74774. get: function () {
  74775. return this._imageProcessingConfiguration;
  74776. },
  74777. /**
  74778. * Sets the Default image processing configuration used either in the this material.
  74779. *
  74780. * If sets to null, the scene one is in use.
  74781. */
  74782. set: function (value) {
  74783. this._attachImageProcessingConfiguration(value);
  74784. },
  74785. enumerable: true,
  74786. configurable: true
  74787. });
  74788. /**
  74789. * Attaches a new image processing configuration to the PBR Material.
  74790. * @param configuration
  74791. */
  74792. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  74793. var _this = this;
  74794. if (doNotBuild === void 0) { doNotBuild = false; }
  74795. if (configuration === this._imageProcessingConfiguration) {
  74796. return;
  74797. }
  74798. // Detaches observer.
  74799. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  74800. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  74801. }
  74802. // Pick the scene configuration if needed.
  74803. if (!configuration) {
  74804. var scene = null;
  74805. var engine = this.getEngine();
  74806. var camera = this.getCamera();
  74807. if (camera) {
  74808. scene = camera.getScene();
  74809. }
  74810. else if (engine && engine.scenes) {
  74811. var scenes = engine.scenes;
  74812. scene = scenes[scenes.length - 1];
  74813. }
  74814. else {
  74815. scene = BABYLON.Engine.LastCreatedScene;
  74816. }
  74817. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  74818. }
  74819. else {
  74820. this._imageProcessingConfiguration = configuration;
  74821. }
  74822. // Attaches observer.
  74823. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  74824. _this._updateParameters();
  74825. });
  74826. // Ensure the effect will be rebuilt.
  74827. if (!doNotBuild) {
  74828. this._updateParameters();
  74829. }
  74830. };
  74831. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  74832. /**
  74833. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  74834. */
  74835. get: function () {
  74836. return this.imageProcessingConfiguration.colorCurves;
  74837. },
  74838. /**
  74839. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  74840. */
  74841. set: function (value) {
  74842. this.imageProcessingConfiguration.colorCurves = value;
  74843. },
  74844. enumerable: true,
  74845. configurable: true
  74846. });
  74847. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  74848. /**
  74849. * Gets wether the color curves effect is enabled.
  74850. */
  74851. get: function () {
  74852. return this.imageProcessingConfiguration.colorCurvesEnabled;
  74853. },
  74854. /**
  74855. * Sets wether the color curves effect is enabled.
  74856. */
  74857. set: function (value) {
  74858. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  74859. },
  74860. enumerable: true,
  74861. configurable: true
  74862. });
  74863. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  74864. /**
  74865. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  74866. */
  74867. get: function () {
  74868. return this.imageProcessingConfiguration.colorGradingTexture;
  74869. },
  74870. /**
  74871. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  74872. */
  74873. set: function (value) {
  74874. this.imageProcessingConfiguration.colorGradingTexture = value;
  74875. },
  74876. enumerable: true,
  74877. configurable: true
  74878. });
  74879. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  74880. /**
  74881. * Gets wether the color grading effect is enabled.
  74882. */
  74883. get: function () {
  74884. return this.imageProcessingConfiguration.colorGradingEnabled;
  74885. },
  74886. /**
  74887. * Gets wether the color grading effect is enabled.
  74888. */
  74889. set: function (value) {
  74890. this.imageProcessingConfiguration.colorGradingEnabled = value;
  74891. },
  74892. enumerable: true,
  74893. configurable: true
  74894. });
  74895. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  74896. /**
  74897. * Gets exposure used in the effect.
  74898. */
  74899. get: function () {
  74900. return this.imageProcessingConfiguration.exposure;
  74901. },
  74902. /**
  74903. * Sets exposure used in the effect.
  74904. */
  74905. set: function (value) {
  74906. this.imageProcessingConfiguration.exposure = value;
  74907. },
  74908. enumerable: true,
  74909. configurable: true
  74910. });
  74911. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  74912. /**
  74913. * Gets wether tonemapping is enabled or not.
  74914. */
  74915. get: function () {
  74916. return this._imageProcessingConfiguration.toneMappingEnabled;
  74917. },
  74918. /**
  74919. * Sets wether tonemapping is enabled or not
  74920. */
  74921. set: function (value) {
  74922. this._imageProcessingConfiguration.toneMappingEnabled = value;
  74923. },
  74924. enumerable: true,
  74925. configurable: true
  74926. });
  74927. ;
  74928. ;
  74929. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  74930. /**
  74931. * Gets contrast used in the effect.
  74932. */
  74933. get: function () {
  74934. return this.imageProcessingConfiguration.contrast;
  74935. },
  74936. /**
  74937. * Sets contrast used in the effect.
  74938. */
  74939. set: function (value) {
  74940. this.imageProcessingConfiguration.contrast = value;
  74941. },
  74942. enumerable: true,
  74943. configurable: true
  74944. });
  74945. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  74946. /**
  74947. * Gets Vignette stretch size.
  74948. */
  74949. get: function () {
  74950. return this.imageProcessingConfiguration.vignetteStretch;
  74951. },
  74952. /**
  74953. * Sets Vignette stretch size.
  74954. */
  74955. set: function (value) {
  74956. this.imageProcessingConfiguration.vignetteStretch = value;
  74957. },
  74958. enumerable: true,
  74959. configurable: true
  74960. });
  74961. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  74962. /**
  74963. * Gets Vignette centre X Offset.
  74964. */
  74965. get: function () {
  74966. return this.imageProcessingConfiguration.vignetteCentreX;
  74967. },
  74968. /**
  74969. * Sets Vignette centre X Offset.
  74970. */
  74971. set: function (value) {
  74972. this.imageProcessingConfiguration.vignetteCentreX = value;
  74973. },
  74974. enumerable: true,
  74975. configurable: true
  74976. });
  74977. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  74978. /**
  74979. * Gets Vignette centre Y Offset.
  74980. */
  74981. get: function () {
  74982. return this.imageProcessingConfiguration.vignetteCentreY;
  74983. },
  74984. /**
  74985. * Sets Vignette centre Y Offset.
  74986. */
  74987. set: function (value) {
  74988. this.imageProcessingConfiguration.vignetteCentreY = value;
  74989. },
  74990. enumerable: true,
  74991. configurable: true
  74992. });
  74993. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  74994. /**
  74995. * Gets Vignette weight or intensity of the vignette effect.
  74996. */
  74997. get: function () {
  74998. return this.imageProcessingConfiguration.vignetteWeight;
  74999. },
  75000. /**
  75001. * Sets Vignette weight or intensity of the vignette effect.
  75002. */
  75003. set: function (value) {
  75004. this.imageProcessingConfiguration.vignetteWeight = value;
  75005. },
  75006. enumerable: true,
  75007. configurable: true
  75008. });
  75009. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  75010. /**
  75011. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  75012. * if vignetteEnabled is set to true.
  75013. */
  75014. get: function () {
  75015. return this.imageProcessingConfiguration.vignetteColor;
  75016. },
  75017. /**
  75018. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  75019. * if vignetteEnabled is set to true.
  75020. */
  75021. set: function (value) {
  75022. this.imageProcessingConfiguration.vignetteColor = value;
  75023. },
  75024. enumerable: true,
  75025. configurable: true
  75026. });
  75027. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  75028. /**
  75029. * Gets Camera field of view used by the Vignette effect.
  75030. */
  75031. get: function () {
  75032. return this.imageProcessingConfiguration.vignetteCameraFov;
  75033. },
  75034. /**
  75035. * Sets Camera field of view used by the Vignette effect.
  75036. */
  75037. set: function (value) {
  75038. this.imageProcessingConfiguration.vignetteCameraFov = value;
  75039. },
  75040. enumerable: true,
  75041. configurable: true
  75042. });
  75043. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  75044. /**
  75045. * Gets the vignette blend mode allowing different kind of effect.
  75046. */
  75047. get: function () {
  75048. return this.imageProcessingConfiguration.vignetteBlendMode;
  75049. },
  75050. /**
  75051. * Sets the vignette blend mode allowing different kind of effect.
  75052. */
  75053. set: function (value) {
  75054. this.imageProcessingConfiguration.vignetteBlendMode = value;
  75055. },
  75056. enumerable: true,
  75057. configurable: true
  75058. });
  75059. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  75060. /**
  75061. * Gets wether the vignette effect is enabled.
  75062. */
  75063. get: function () {
  75064. return this.imageProcessingConfiguration.vignetteEnabled;
  75065. },
  75066. /**
  75067. * Sets wether the vignette effect is enabled.
  75068. */
  75069. set: function (value) {
  75070. this.imageProcessingConfiguration.vignetteEnabled = value;
  75071. },
  75072. enumerable: true,
  75073. configurable: true
  75074. });
  75075. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  75076. /**
  75077. * Gets wether the input of the processing is in Gamma or Linear Space.
  75078. */
  75079. get: function () {
  75080. return this._fromLinearSpace;
  75081. },
  75082. /**
  75083. * Sets wether the input of the processing is in Gamma or Linear Space.
  75084. */
  75085. set: function (value) {
  75086. if (this._fromLinearSpace === value) {
  75087. return;
  75088. }
  75089. this._fromLinearSpace = value;
  75090. this._updateParameters();
  75091. },
  75092. enumerable: true,
  75093. configurable: true
  75094. });
  75095. ImageProcessingPostProcess.prototype.getClassName = function () {
  75096. return "ImageProcessingPostProcess";
  75097. };
  75098. ImageProcessingPostProcess.prototype._updateParameters = function () {
  75099. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  75100. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  75101. var defines = "";
  75102. for (var define in this._defines) {
  75103. if (this._defines[define]) {
  75104. defines += "#define " + define + ";\r\n";
  75105. }
  75106. }
  75107. var samplers = ["textureSampler"];
  75108. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  75109. var uniforms = ["scale"];
  75110. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  75111. this.updateEffect(defines, uniforms, samplers);
  75112. };
  75113. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  75114. _super.prototype.dispose.call(this, camera);
  75115. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  75116. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  75117. }
  75118. this.imageProcessingConfiguration.applyByPostProcess = false;
  75119. };
  75120. __decorate([
  75121. BABYLON.serialize()
  75122. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  75123. return ImageProcessingPostProcess;
  75124. }(BABYLON.PostProcess));
  75125. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  75126. })(BABYLON || (BABYLON = {}));
  75127. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  75128. "use strict";
  75129. var BABYLON;
  75130. (function (BABYLON) {
  75131. var Bone = /** @class */ (function (_super) {
  75132. __extends(Bone, _super);
  75133. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  75134. if (parentBone === void 0) { parentBone = null; }
  75135. if (localMatrix === void 0) { localMatrix = null; }
  75136. if (restPose === void 0) { restPose = null; }
  75137. if (baseMatrix === void 0) { baseMatrix = null; }
  75138. if (index === void 0) { index = null; }
  75139. var _this = _super.call(this, name, skeleton.getScene()) || this;
  75140. _this.name = name;
  75141. _this.children = new Array();
  75142. _this.animations = new Array();
  75143. // Set this value to map this bone to a different index in the transform matrices.
  75144. // Set this value to -1 to exclude the bone from the transform matrices.
  75145. _this._index = null;
  75146. _this._worldTransform = new BABYLON.Matrix();
  75147. _this._absoluteTransform = new BABYLON.Matrix();
  75148. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  75149. _this._scaleMatrix = BABYLON.Matrix.Identity();
  75150. _this._scaleVector = BABYLON.Vector3.One();
  75151. _this._negateScaleChildren = BABYLON.Vector3.One();
  75152. _this._scalingDeterminant = 1;
  75153. _this._skeleton = skeleton;
  75154. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  75155. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  75156. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  75157. _this._index = index;
  75158. skeleton.bones.push(_this);
  75159. _this.setParent(parentBone, false);
  75160. _this._updateDifferenceMatrix();
  75161. return _this;
  75162. }
  75163. Object.defineProperty(Bone.prototype, "_matrix", {
  75164. get: function () {
  75165. return this._localMatrix;
  75166. },
  75167. set: function (val) {
  75168. if (this._localMatrix) {
  75169. this._localMatrix.copyFrom(val);
  75170. }
  75171. else {
  75172. this._localMatrix = val;
  75173. }
  75174. },
  75175. enumerable: true,
  75176. configurable: true
  75177. });
  75178. // Members
  75179. Bone.prototype.getSkeleton = function () {
  75180. return this._skeleton;
  75181. };
  75182. Bone.prototype.getParent = function () {
  75183. return this._parent;
  75184. };
  75185. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  75186. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  75187. if (this._parent === parent) {
  75188. return;
  75189. }
  75190. if (this._parent) {
  75191. var index = this._parent.children.indexOf(this);
  75192. if (index !== -1) {
  75193. this._parent.children.splice(index, 1);
  75194. }
  75195. }
  75196. this._parent = parent;
  75197. if (this._parent) {
  75198. this._parent.children.push(this);
  75199. }
  75200. if (updateDifferenceMatrix) {
  75201. this._updateDifferenceMatrix();
  75202. }
  75203. };
  75204. Bone.prototype.getLocalMatrix = function () {
  75205. return this._localMatrix;
  75206. };
  75207. Bone.prototype.getBaseMatrix = function () {
  75208. return this._baseMatrix;
  75209. };
  75210. Bone.prototype.getRestPose = function () {
  75211. return this._restPose;
  75212. };
  75213. Bone.prototype.returnToRest = function () {
  75214. this.updateMatrix(this._restPose.clone());
  75215. };
  75216. Bone.prototype.getWorldMatrix = function () {
  75217. return this._worldTransform;
  75218. };
  75219. Bone.prototype.getInvertedAbsoluteTransform = function () {
  75220. return this._invertedAbsoluteTransform;
  75221. };
  75222. Bone.prototype.getAbsoluteTransform = function () {
  75223. return this._absoluteTransform;
  75224. };
  75225. Object.defineProperty(Bone.prototype, "position", {
  75226. // Properties (matches AbstractMesh properties)
  75227. get: function () {
  75228. return this.getPosition();
  75229. },
  75230. set: function (newPosition) {
  75231. this.setPosition(newPosition);
  75232. },
  75233. enumerable: true,
  75234. configurable: true
  75235. });
  75236. Object.defineProperty(Bone.prototype, "rotation", {
  75237. get: function () {
  75238. return this.getRotation();
  75239. },
  75240. set: function (newRotation) {
  75241. this.setRotation(newRotation);
  75242. },
  75243. enumerable: true,
  75244. configurable: true
  75245. });
  75246. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  75247. get: function () {
  75248. return this.getRotationQuaternion();
  75249. },
  75250. set: function (newRotation) {
  75251. this.setRotationQuaternion(newRotation);
  75252. },
  75253. enumerable: true,
  75254. configurable: true
  75255. });
  75256. Object.defineProperty(Bone.prototype, "scaling", {
  75257. get: function () {
  75258. return this.getScale();
  75259. },
  75260. set: function (newScaling) {
  75261. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  75262. },
  75263. enumerable: true,
  75264. configurable: true
  75265. });
  75266. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  75267. /**
  75268. * Gets the animation properties override
  75269. */
  75270. get: function () {
  75271. return this._skeleton.animationPropertiesOverride;
  75272. },
  75273. enumerable: true,
  75274. configurable: true
  75275. });
  75276. // Methods
  75277. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  75278. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  75279. this._baseMatrix = matrix.clone();
  75280. this._localMatrix = matrix.clone();
  75281. this._skeleton._markAsDirty();
  75282. if (updateDifferenceMatrix) {
  75283. this._updateDifferenceMatrix();
  75284. }
  75285. };
  75286. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  75287. if (!rootMatrix) {
  75288. rootMatrix = this._baseMatrix;
  75289. }
  75290. if (this._parent) {
  75291. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  75292. }
  75293. else {
  75294. this._absoluteTransform.copyFrom(rootMatrix);
  75295. }
  75296. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  75297. for (var index = 0; index < this.children.length; index++) {
  75298. this.children[index]._updateDifferenceMatrix();
  75299. }
  75300. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  75301. };
  75302. Bone.prototype.markAsDirty = function () {
  75303. this._currentRenderId++;
  75304. this._childRenderId++;
  75305. this._skeleton._markAsDirty();
  75306. };
  75307. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  75308. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  75309. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  75310. // all animation may be coming from a library skeleton, so may need to create animation
  75311. if (this.animations.length === 0) {
  75312. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  75313. this.animations[0].setKeys([]);
  75314. }
  75315. // get animation info / verify there is such a range from the source bone
  75316. var sourceRange = source.animations[0].getRange(rangeName);
  75317. if (!sourceRange) {
  75318. return false;
  75319. }
  75320. var from = sourceRange.from;
  75321. var to = sourceRange.to;
  75322. var sourceKeys = source.animations[0].getKeys();
  75323. // rescaling prep
  75324. var sourceBoneLength = source.length;
  75325. var sourceParent = source.getParent();
  75326. var parent = this.getParent();
  75327. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  75328. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  75329. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  75330. var destKeys = this.animations[0].getKeys();
  75331. // loop vars declaration
  75332. var orig;
  75333. var origTranslation;
  75334. var mat;
  75335. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  75336. orig = sourceKeys[key];
  75337. if (orig.frame >= from && orig.frame <= to) {
  75338. if (rescaleAsRequired) {
  75339. mat = orig.value.clone();
  75340. // scale based on parent ratio, when bone has parent
  75341. if (parentScalingReqd) {
  75342. origTranslation = mat.getTranslation();
  75343. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  75344. // scale based on skeleton dimension ratio when root bone, and value is passed
  75345. }
  75346. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  75347. origTranslation = mat.getTranslation();
  75348. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  75349. // use original when root bone, and no data for skelDimensionsRatio
  75350. }
  75351. else {
  75352. mat = orig.value;
  75353. }
  75354. }
  75355. else {
  75356. mat = orig.value;
  75357. }
  75358. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  75359. }
  75360. }
  75361. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  75362. return true;
  75363. };
  75364. /**
  75365. * Translate the bone in local or world space.
  75366. * @param vec The amount to translate the bone.
  75367. * @param space The space that the translation is in.
  75368. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  75369. */
  75370. Bone.prototype.translate = function (vec, space, mesh) {
  75371. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75372. var lm = this.getLocalMatrix();
  75373. if (space == BABYLON.Space.LOCAL) {
  75374. lm.m[12] += vec.x;
  75375. lm.m[13] += vec.y;
  75376. lm.m[14] += vec.z;
  75377. }
  75378. else {
  75379. var wm = null;
  75380. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  75381. if (mesh) {
  75382. wm = mesh.getWorldMatrix();
  75383. }
  75384. this._skeleton.computeAbsoluteTransforms();
  75385. var tmat = Bone._tmpMats[0];
  75386. var tvec = Bone._tmpVecs[0];
  75387. if (this._parent) {
  75388. if (mesh && wm) {
  75389. tmat.copyFrom(this._parent.getAbsoluteTransform());
  75390. tmat.multiplyToRef(wm, tmat);
  75391. }
  75392. else {
  75393. tmat.copyFrom(this._parent.getAbsoluteTransform());
  75394. }
  75395. }
  75396. tmat.m[12] = 0;
  75397. tmat.m[13] = 0;
  75398. tmat.m[14] = 0;
  75399. tmat.invert();
  75400. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  75401. lm.m[12] += tvec.x;
  75402. lm.m[13] += tvec.y;
  75403. lm.m[14] += tvec.z;
  75404. }
  75405. this.markAsDirty();
  75406. };
  75407. /**
  75408. * Set the postion of the bone in local or world space.
  75409. * @param position The position to set the bone.
  75410. * @param space The space that the position is in.
  75411. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  75412. */
  75413. Bone.prototype.setPosition = function (position, space, mesh) {
  75414. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75415. var lm = this.getLocalMatrix();
  75416. if (space == BABYLON.Space.LOCAL) {
  75417. lm.m[12] = position.x;
  75418. lm.m[13] = position.y;
  75419. lm.m[14] = position.z;
  75420. }
  75421. else {
  75422. var wm = null;
  75423. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  75424. if (mesh) {
  75425. wm = mesh.getWorldMatrix();
  75426. }
  75427. this._skeleton.computeAbsoluteTransforms();
  75428. var tmat = Bone._tmpMats[0];
  75429. var vec = Bone._tmpVecs[0];
  75430. if (this._parent) {
  75431. if (mesh && wm) {
  75432. tmat.copyFrom(this._parent.getAbsoluteTransform());
  75433. tmat.multiplyToRef(wm, tmat);
  75434. }
  75435. else {
  75436. tmat.copyFrom(this._parent.getAbsoluteTransform());
  75437. }
  75438. }
  75439. tmat.invert();
  75440. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  75441. lm.m[12] = vec.x;
  75442. lm.m[13] = vec.y;
  75443. lm.m[14] = vec.z;
  75444. }
  75445. this.markAsDirty();
  75446. };
  75447. /**
  75448. * Set the absolute postion of the bone (world space).
  75449. * @param position The position to set the bone.
  75450. * @param mesh The mesh that this bone is attached to.
  75451. */
  75452. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  75453. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  75454. };
  75455. /**
  75456. * Set the scale of the bone on the x, y and z axes.
  75457. * @param x The scale of the bone on the x axis.
  75458. * @param x The scale of the bone on the y axis.
  75459. * @param z The scale of the bone on the z axis.
  75460. * @param scaleChildren Set this to true if children of the bone should be scaled.
  75461. */
  75462. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  75463. if (scaleChildren === void 0) { scaleChildren = false; }
  75464. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  75465. if (!scaleChildren) {
  75466. this._negateScaleChildren.x = 1 / x;
  75467. this._negateScaleChildren.y = 1 / y;
  75468. this._negateScaleChildren.z = 1 / z;
  75469. }
  75470. this._syncScaleVector();
  75471. }
  75472. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  75473. };
  75474. /**
  75475. * Scale the bone on the x, y and z axes.
  75476. * @param x The amount to scale the bone on the x axis.
  75477. * @param x The amount to scale the bone on the y axis.
  75478. * @param z The amount to scale the bone on the z axis.
  75479. * @param scaleChildren Set this to true if children of the bone should be scaled.
  75480. */
  75481. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  75482. if (scaleChildren === void 0) { scaleChildren = false; }
  75483. var locMat = this.getLocalMatrix();
  75484. var origLocMat = Bone._tmpMats[0];
  75485. origLocMat.copyFrom(locMat);
  75486. var origLocMatInv = Bone._tmpMats[1];
  75487. origLocMatInv.copyFrom(origLocMat);
  75488. origLocMatInv.invert();
  75489. var scaleMat = Bone._tmpMats[2];
  75490. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  75491. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  75492. this._scaleVector.x *= x;
  75493. this._scaleVector.y *= y;
  75494. this._scaleVector.z *= z;
  75495. locMat.multiplyToRef(origLocMatInv, locMat);
  75496. locMat.multiplyToRef(scaleMat, locMat);
  75497. locMat.multiplyToRef(origLocMat, locMat);
  75498. var parent = this.getParent();
  75499. if (parent) {
  75500. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  75501. }
  75502. else {
  75503. this.getAbsoluteTransform().copyFrom(locMat);
  75504. }
  75505. var len = this.children.length;
  75506. scaleMat.invert();
  75507. for (var i = 0; i < len; i++) {
  75508. var child = this.children[i];
  75509. var cm = child.getLocalMatrix();
  75510. cm.multiplyToRef(scaleMat, cm);
  75511. var lm = child.getLocalMatrix();
  75512. lm.m[12] *= x;
  75513. lm.m[13] *= y;
  75514. lm.m[14] *= z;
  75515. }
  75516. this.computeAbsoluteTransforms();
  75517. if (scaleChildren) {
  75518. for (var i = 0; i < len; i++) {
  75519. this.children[i].scale(x, y, z, scaleChildren);
  75520. }
  75521. }
  75522. this.markAsDirty();
  75523. };
  75524. /**
  75525. * Set the yaw, pitch, and roll of the bone in local or world space.
  75526. * @param yaw The rotation of the bone on the y axis.
  75527. * @param pitch The rotation of the bone on the x axis.
  75528. * @param roll The rotation of the bone on the z axis.
  75529. * @param space The space that the axes of rotation are in.
  75530. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  75531. */
  75532. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  75533. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75534. var rotMat = Bone._tmpMats[0];
  75535. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  75536. var rotMatInv = Bone._tmpMats[1];
  75537. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  75538. rotMatInv.multiplyToRef(rotMat, rotMat);
  75539. this._rotateWithMatrix(rotMat, space, mesh);
  75540. };
  75541. /**
  75542. * Rotate the bone on an axis in local or world space.
  75543. * @param axis The axis to rotate the bone on.
  75544. * @param amount The amount to rotate the bone.
  75545. * @param space The space that the axis is in.
  75546. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  75547. */
  75548. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  75549. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75550. var rmat = Bone._tmpMats[0];
  75551. rmat.m[12] = 0;
  75552. rmat.m[13] = 0;
  75553. rmat.m[14] = 0;
  75554. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  75555. this._rotateWithMatrix(rmat, space, mesh);
  75556. };
  75557. /**
  75558. * Set the rotation of the bone to a particular axis angle in local or world space.
  75559. * @param axis The axis to rotate the bone on.
  75560. * @param angle The angle that the bone should be rotated to.
  75561. * @param space The space that the axis is in.
  75562. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  75563. */
  75564. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  75565. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75566. var rotMat = Bone._tmpMats[0];
  75567. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  75568. var rotMatInv = Bone._tmpMats[1];
  75569. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  75570. rotMatInv.multiplyToRef(rotMat, rotMat);
  75571. this._rotateWithMatrix(rotMat, space, mesh);
  75572. };
  75573. /**
  75574. * Set the euler rotation of the bone in local of world space.
  75575. * @param rotation The euler rotation that the bone should be set to.
  75576. * @param space The space that the rotation is in.
  75577. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  75578. */
  75579. Bone.prototype.setRotation = function (rotation, space, mesh) {
  75580. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75581. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  75582. };
  75583. /**
  75584. * Set the quaternion rotation of the bone in local of world space.
  75585. * @param quat The quaternion rotation that the bone should be set to.
  75586. * @param space The space that the rotation is in.
  75587. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  75588. */
  75589. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  75590. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75591. var rotMatInv = Bone._tmpMats[0];
  75592. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  75593. var rotMat = Bone._tmpMats[1];
  75594. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  75595. rotMatInv.multiplyToRef(rotMat, rotMat);
  75596. this._rotateWithMatrix(rotMat, space, mesh);
  75597. };
  75598. /**
  75599. * Set the rotation matrix of the bone in local of world space.
  75600. * @param rotMat The rotation matrix that the bone should be set to.
  75601. * @param space The space that the rotation is in.
  75602. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  75603. */
  75604. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  75605. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75606. var rotMatInv = Bone._tmpMats[0];
  75607. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  75608. var rotMat2 = Bone._tmpMats[1];
  75609. rotMat2.copyFrom(rotMat);
  75610. rotMatInv.multiplyToRef(rotMat, rotMat2);
  75611. this._rotateWithMatrix(rotMat2, space, mesh);
  75612. };
  75613. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  75614. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75615. var lmat = this.getLocalMatrix();
  75616. var lx = lmat.m[12];
  75617. var ly = lmat.m[13];
  75618. var lz = lmat.m[14];
  75619. var parent = this.getParent();
  75620. var parentScale = Bone._tmpMats[3];
  75621. var parentScaleInv = Bone._tmpMats[4];
  75622. if (parent) {
  75623. if (space == BABYLON.Space.WORLD) {
  75624. if (mesh) {
  75625. parentScale.copyFrom(mesh.getWorldMatrix());
  75626. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  75627. }
  75628. else {
  75629. parentScale.copyFrom(parent.getAbsoluteTransform());
  75630. }
  75631. }
  75632. else {
  75633. parentScale = parent._scaleMatrix;
  75634. }
  75635. parentScaleInv.copyFrom(parentScale);
  75636. parentScaleInv.invert();
  75637. lmat.multiplyToRef(parentScale, lmat);
  75638. lmat.multiplyToRef(rmat, lmat);
  75639. lmat.multiplyToRef(parentScaleInv, lmat);
  75640. }
  75641. else {
  75642. if (space == BABYLON.Space.WORLD && mesh) {
  75643. parentScale.copyFrom(mesh.getWorldMatrix());
  75644. parentScaleInv.copyFrom(parentScale);
  75645. parentScaleInv.invert();
  75646. lmat.multiplyToRef(parentScale, lmat);
  75647. lmat.multiplyToRef(rmat, lmat);
  75648. lmat.multiplyToRef(parentScaleInv, lmat);
  75649. }
  75650. else {
  75651. lmat.multiplyToRef(rmat, lmat);
  75652. }
  75653. }
  75654. lmat.m[12] = lx;
  75655. lmat.m[13] = ly;
  75656. lmat.m[14] = lz;
  75657. this.computeAbsoluteTransforms();
  75658. this.markAsDirty();
  75659. };
  75660. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  75661. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75662. if (space == BABYLON.Space.WORLD) {
  75663. var scaleMatrix = Bone._tmpMats[2];
  75664. scaleMatrix.copyFrom(this._scaleMatrix);
  75665. rotMatInv.copyFrom(this.getAbsoluteTransform());
  75666. if (mesh) {
  75667. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  75668. var meshScale = Bone._tmpMats[3];
  75669. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  75670. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  75671. }
  75672. rotMatInv.invert();
  75673. scaleMatrix.m[0] *= this._scalingDeterminant;
  75674. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  75675. }
  75676. else {
  75677. rotMatInv.copyFrom(this.getLocalMatrix());
  75678. rotMatInv.invert();
  75679. var scaleMatrix = Bone._tmpMats[2];
  75680. scaleMatrix.copyFrom(this._scaleMatrix);
  75681. if (this._parent) {
  75682. var pscaleMatrix = Bone._tmpMats[3];
  75683. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  75684. pscaleMatrix.invert();
  75685. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  75686. }
  75687. else {
  75688. scaleMatrix.m[0] *= this._scalingDeterminant;
  75689. }
  75690. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  75691. }
  75692. };
  75693. /**
  75694. * Get the scale of the bone
  75695. * @returns the scale of the bone
  75696. */
  75697. Bone.prototype.getScale = function () {
  75698. return this._scaleVector.clone();
  75699. };
  75700. /**
  75701. * Copy the scale of the bone to a vector3.
  75702. * @param result The vector3 to copy the scale to
  75703. */
  75704. Bone.prototype.getScaleToRef = function (result) {
  75705. result.copyFrom(this._scaleVector);
  75706. };
  75707. /**
  75708. * Get the position of the bone in local or world space.
  75709. * @param space The space that the returned position is in.
  75710. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  75711. * @returns The position of the bone
  75712. */
  75713. Bone.prototype.getPosition = function (space, mesh) {
  75714. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75715. if (mesh === void 0) { mesh = null; }
  75716. var pos = BABYLON.Vector3.Zero();
  75717. this.getPositionToRef(space, mesh, pos);
  75718. return pos;
  75719. };
  75720. /**
  75721. * Copy the position of the bone to a vector3 in local or world space.
  75722. * @param space The space that the returned position is in.
  75723. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  75724. * @param result The vector3 to copy the position to.
  75725. */
  75726. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  75727. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75728. if (space == BABYLON.Space.LOCAL) {
  75729. var lm = this.getLocalMatrix();
  75730. result.x = lm.m[12];
  75731. result.y = lm.m[13];
  75732. result.z = lm.m[14];
  75733. }
  75734. else {
  75735. var wm = null;
  75736. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  75737. if (mesh) {
  75738. wm = mesh.getWorldMatrix();
  75739. }
  75740. this._skeleton.computeAbsoluteTransforms();
  75741. var tmat = Bone._tmpMats[0];
  75742. if (mesh && wm) {
  75743. tmat.copyFrom(this.getAbsoluteTransform());
  75744. tmat.multiplyToRef(wm, tmat);
  75745. }
  75746. else {
  75747. tmat = this.getAbsoluteTransform();
  75748. }
  75749. result.x = tmat.m[12];
  75750. result.y = tmat.m[13];
  75751. result.z = tmat.m[14];
  75752. }
  75753. };
  75754. /**
  75755. * Get the absolute position of the bone (world space).
  75756. * @param mesh The mesh that this bone is attached to.
  75757. * @returns The absolute position of the bone
  75758. */
  75759. Bone.prototype.getAbsolutePosition = function (mesh) {
  75760. if (mesh === void 0) { mesh = null; }
  75761. var pos = BABYLON.Vector3.Zero();
  75762. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  75763. return pos;
  75764. };
  75765. /**
  75766. * Copy the absolute position of the bone (world space) to the result param.
  75767. * @param mesh The mesh that this bone is attached to.
  75768. * @param result The vector3 to copy the absolute position to.
  75769. */
  75770. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  75771. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  75772. };
  75773. /**
  75774. * Compute the absolute transforms of this bone and its children.
  75775. */
  75776. Bone.prototype.computeAbsoluteTransforms = function () {
  75777. if (this._parent) {
  75778. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  75779. }
  75780. else {
  75781. this._absoluteTransform.copyFrom(this._localMatrix);
  75782. var poseMatrix = this._skeleton.getPoseMatrix();
  75783. if (poseMatrix) {
  75784. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  75785. }
  75786. }
  75787. var children = this.children;
  75788. var len = children.length;
  75789. for (var i = 0; i < len; i++) {
  75790. children[i].computeAbsoluteTransforms();
  75791. }
  75792. };
  75793. Bone.prototype._syncScaleVector = function () {
  75794. var lm = this.getLocalMatrix();
  75795. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  75796. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  75797. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  75798. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  75799. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  75800. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  75801. this._scaleVector.x = xs * Math.sqrt(xsq);
  75802. this._scaleVector.y = ys * Math.sqrt(ysq);
  75803. this._scaleVector.z = zs * Math.sqrt(zsq);
  75804. if (this._parent) {
  75805. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  75806. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  75807. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  75808. }
  75809. 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);
  75810. };
  75811. /**
  75812. * Get the world direction from an axis that is in the local space of the bone.
  75813. * @param localAxis The local direction that is used to compute the world direction.
  75814. * @param mesh The mesh that this bone is attached to.
  75815. * @returns The world direction
  75816. */
  75817. Bone.prototype.getDirection = function (localAxis, mesh) {
  75818. if (mesh === void 0) { mesh = null; }
  75819. var result = BABYLON.Vector3.Zero();
  75820. this.getDirectionToRef(localAxis, mesh, result);
  75821. return result;
  75822. };
  75823. /**
  75824. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  75825. * @param localAxis The local direction that is used to compute the world direction.
  75826. * @param mesh The mesh that this bone is attached to.
  75827. * @param result The vector3 that the world direction will be copied to.
  75828. */
  75829. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  75830. if (mesh === void 0) { mesh = null; }
  75831. var wm = null;
  75832. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  75833. if (mesh) {
  75834. wm = mesh.getWorldMatrix();
  75835. }
  75836. this._skeleton.computeAbsoluteTransforms();
  75837. var mat = Bone._tmpMats[0];
  75838. mat.copyFrom(this.getAbsoluteTransform());
  75839. if (mesh && wm) {
  75840. mat.multiplyToRef(wm, mat);
  75841. }
  75842. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  75843. result.normalize();
  75844. };
  75845. /**
  75846. * Get the euler rotation of the bone in local or world space.
  75847. * @param space The space that the rotation should be in.
  75848. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  75849. * @returns The euler rotation
  75850. */
  75851. Bone.prototype.getRotation = function (space, mesh) {
  75852. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75853. if (mesh === void 0) { mesh = null; }
  75854. var result = BABYLON.Vector3.Zero();
  75855. this.getRotationToRef(space, mesh, result);
  75856. return result;
  75857. };
  75858. /**
  75859. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  75860. * @param space The space that the rotation should be in.
  75861. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  75862. * @param result The vector3 that the rotation should be copied to.
  75863. */
  75864. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  75865. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75866. if (mesh === void 0) { mesh = null; }
  75867. var quat = Bone._tmpQuat;
  75868. this.getRotationQuaternionToRef(space, mesh, quat);
  75869. quat.toEulerAnglesToRef(result);
  75870. };
  75871. /**
  75872. * Get the quaternion rotation of the bone in either local or world space.
  75873. * @param space The space that the rotation should be in.
  75874. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  75875. * @returns The quaternion rotation
  75876. */
  75877. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  75878. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75879. if (mesh === void 0) { mesh = null; }
  75880. var result = BABYLON.Quaternion.Identity();
  75881. this.getRotationQuaternionToRef(space, mesh, result);
  75882. return result;
  75883. };
  75884. /**
  75885. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  75886. * @param space The space that the rotation should be in.
  75887. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  75888. * @param result The quaternion that the rotation should be copied to.
  75889. */
  75890. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  75891. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75892. if (mesh === void 0) { mesh = null; }
  75893. if (space == BABYLON.Space.LOCAL) {
  75894. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  75895. }
  75896. else {
  75897. var mat = Bone._tmpMats[0];
  75898. var amat = this.getAbsoluteTransform();
  75899. if (mesh) {
  75900. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  75901. }
  75902. else {
  75903. mat.copyFrom(amat);
  75904. }
  75905. mat.m[0] *= this._scalingDeterminant;
  75906. mat.m[1] *= this._scalingDeterminant;
  75907. mat.m[2] *= this._scalingDeterminant;
  75908. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  75909. }
  75910. };
  75911. /**
  75912. * Get the rotation matrix of the bone in local or world space.
  75913. * @param space The space that the rotation should be in.
  75914. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  75915. * @returns The rotation matrix
  75916. */
  75917. Bone.prototype.getRotationMatrix = function (space, mesh) {
  75918. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75919. var result = BABYLON.Matrix.Identity();
  75920. this.getRotationMatrixToRef(space, mesh, result);
  75921. return result;
  75922. };
  75923. /**
  75924. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  75925. * @param space The space that the rotation should be in.
  75926. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  75927. * @param result The quaternion that the rotation should be copied to.
  75928. */
  75929. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  75930. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75931. if (space == BABYLON.Space.LOCAL) {
  75932. this.getLocalMatrix().getRotationMatrixToRef(result);
  75933. }
  75934. else {
  75935. var mat = Bone._tmpMats[0];
  75936. var amat = this.getAbsoluteTransform();
  75937. if (mesh) {
  75938. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  75939. }
  75940. else {
  75941. mat.copyFrom(amat);
  75942. }
  75943. mat.m[0] *= this._scalingDeterminant;
  75944. mat.m[1] *= this._scalingDeterminant;
  75945. mat.m[2] *= this._scalingDeterminant;
  75946. mat.getRotationMatrixToRef(result);
  75947. }
  75948. };
  75949. /**
  75950. * Get the world position of a point that is in the local space of the bone.
  75951. * @param position The local position
  75952. * @param mesh The mesh that this bone is attached to.
  75953. * @returns The world position
  75954. */
  75955. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  75956. if (mesh === void 0) { mesh = null; }
  75957. var result = BABYLON.Vector3.Zero();
  75958. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  75959. return result;
  75960. };
  75961. /**
  75962. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  75963. * @param position The local position
  75964. * @param mesh The mesh that this bone is attached to.
  75965. * @param result The vector3 that the world position should be copied to.
  75966. */
  75967. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  75968. if (mesh === void 0) { mesh = null; }
  75969. var wm = null;
  75970. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  75971. if (mesh) {
  75972. wm = mesh.getWorldMatrix();
  75973. }
  75974. this._skeleton.computeAbsoluteTransforms();
  75975. var tmat = Bone._tmpMats[0];
  75976. if (mesh && wm) {
  75977. tmat.copyFrom(this.getAbsoluteTransform());
  75978. tmat.multiplyToRef(wm, tmat);
  75979. }
  75980. else {
  75981. tmat = this.getAbsoluteTransform();
  75982. }
  75983. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  75984. };
  75985. /**
  75986. * Get the local position of a point that is in world space.
  75987. * @param position The world position
  75988. * @param mesh The mesh that this bone is attached to.
  75989. * @returns The local position
  75990. */
  75991. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  75992. if (mesh === void 0) { mesh = null; }
  75993. var result = BABYLON.Vector3.Zero();
  75994. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  75995. return result;
  75996. };
  75997. /**
  75998. * Get the local position of a point that is in world space and copy it to the result param.
  75999. * @param position The world position
  76000. * @param mesh The mesh that this bone is attached to.
  76001. * @param result The vector3 that the local position should be copied to.
  76002. */
  76003. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  76004. if (mesh === void 0) { mesh = null; }
  76005. var wm = null;
  76006. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  76007. if (mesh) {
  76008. wm = mesh.getWorldMatrix();
  76009. }
  76010. this._skeleton.computeAbsoluteTransforms();
  76011. var tmat = Bone._tmpMats[0];
  76012. tmat.copyFrom(this.getAbsoluteTransform());
  76013. if (mesh && wm) {
  76014. tmat.multiplyToRef(wm, tmat);
  76015. }
  76016. tmat.invert();
  76017. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  76018. };
  76019. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76020. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  76021. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  76022. return Bone;
  76023. }(BABYLON.Node));
  76024. BABYLON.Bone = Bone;
  76025. })(BABYLON || (BABYLON = {}));
  76026. //# sourceMappingURL=babylon.bone.js.map
  76027. "use strict";
  76028. var BABYLON;
  76029. (function (BABYLON) {
  76030. var BoneIKController = /** @class */ (function () {
  76031. function BoneIKController(mesh, bone, options) {
  76032. this.targetPosition = BABYLON.Vector3.Zero();
  76033. this.poleTargetPosition = BABYLON.Vector3.Zero();
  76034. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  76035. this.poleAngle = 0;
  76036. this.slerpAmount = 1;
  76037. this._bone1Quat = BABYLON.Quaternion.Identity();
  76038. this._bone1Mat = BABYLON.Matrix.Identity();
  76039. this._bone2Ang = Math.PI;
  76040. this._maxAngle = Math.PI;
  76041. this._rightHandedSystem = false;
  76042. this._bendAxis = BABYLON.Vector3.Right();
  76043. this._slerping = false;
  76044. this._adjustRoll = 0;
  76045. this._bone2 = bone;
  76046. this._bone1 = bone.getParent();
  76047. if (!this._bone1) {
  76048. return;
  76049. }
  76050. this.mesh = mesh;
  76051. var bonePos = bone.getPosition();
  76052. if (bone.getAbsoluteTransform().determinant() > 0) {
  76053. this._rightHandedSystem = true;
  76054. this._bendAxis.x = 0;
  76055. this._bendAxis.y = 0;
  76056. this._bendAxis.z = -1;
  76057. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  76058. this._adjustRoll = Math.PI * .5;
  76059. this._bendAxis.z = 1;
  76060. }
  76061. }
  76062. if (this._bone1.length) {
  76063. var boneScale1 = this._bone1.getScale();
  76064. var boneScale2 = this._bone2.getScale();
  76065. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  76066. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  76067. }
  76068. else if (this._bone1.children[0]) {
  76069. mesh.computeWorldMatrix(true);
  76070. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  76071. var pos2 = this._bone2.getAbsolutePosition(mesh);
  76072. var pos3 = this._bone1.getAbsolutePosition(mesh);
  76073. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  76074. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  76075. }
  76076. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  76077. this.maxAngle = Math.PI;
  76078. if (options) {
  76079. if (options.targetMesh) {
  76080. this.targetMesh = options.targetMesh;
  76081. this.targetMesh.computeWorldMatrix(true);
  76082. }
  76083. if (options.poleTargetMesh) {
  76084. this.poleTargetMesh = options.poleTargetMesh;
  76085. this.poleTargetMesh.computeWorldMatrix(true);
  76086. }
  76087. else if (options.poleTargetBone) {
  76088. this.poleTargetBone = options.poleTargetBone;
  76089. }
  76090. else if (this._bone1.getParent()) {
  76091. this.poleTargetBone = this._bone1.getParent();
  76092. }
  76093. if (options.poleTargetLocalOffset) {
  76094. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  76095. }
  76096. if (options.poleAngle) {
  76097. this.poleAngle = options.poleAngle;
  76098. }
  76099. if (options.bendAxis) {
  76100. this._bendAxis.copyFrom(options.bendAxis);
  76101. }
  76102. if (options.maxAngle) {
  76103. this.maxAngle = options.maxAngle;
  76104. }
  76105. if (options.slerpAmount) {
  76106. this.slerpAmount = options.slerpAmount;
  76107. }
  76108. }
  76109. }
  76110. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  76111. get: function () {
  76112. return this._maxAngle;
  76113. },
  76114. set: function (value) {
  76115. this._setMaxAngle(value);
  76116. },
  76117. enumerable: true,
  76118. configurable: true
  76119. });
  76120. BoneIKController.prototype._setMaxAngle = function (ang) {
  76121. if (ang < 0) {
  76122. ang = 0;
  76123. }
  76124. if (ang > Math.PI || ang == undefined) {
  76125. ang = Math.PI;
  76126. }
  76127. this._maxAngle = ang;
  76128. var a = this._bone1Length;
  76129. var b = this._bone2Length;
  76130. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  76131. };
  76132. BoneIKController.prototype.update = function () {
  76133. var bone1 = this._bone1;
  76134. if (!bone1) {
  76135. return;
  76136. }
  76137. var target = this.targetPosition;
  76138. var poleTarget = this.poleTargetPosition;
  76139. var mat1 = BoneIKController._tmpMats[0];
  76140. var mat2 = BoneIKController._tmpMats[1];
  76141. if (this.targetMesh) {
  76142. target.copyFrom(this.targetMesh.getAbsolutePosition());
  76143. }
  76144. if (this.poleTargetBone) {
  76145. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  76146. }
  76147. else if (this.poleTargetMesh) {
  76148. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  76149. }
  76150. var bonePos = BoneIKController._tmpVecs[0];
  76151. var zaxis = BoneIKController._tmpVecs[1];
  76152. var xaxis = BoneIKController._tmpVecs[2];
  76153. var yaxis = BoneIKController._tmpVecs[3];
  76154. var upAxis = BoneIKController._tmpVecs[4];
  76155. var _tmpQuat = BoneIKController._tmpQuat;
  76156. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  76157. poleTarget.subtractToRef(bonePos, upAxis);
  76158. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  76159. upAxis.y = 1;
  76160. }
  76161. else {
  76162. upAxis.normalize();
  76163. }
  76164. target.subtractToRef(bonePos, yaxis);
  76165. yaxis.normalize();
  76166. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  76167. zaxis.normalize();
  76168. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  76169. xaxis.normalize();
  76170. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  76171. var a = this._bone1Length;
  76172. var b = this._bone2Length;
  76173. var c = BABYLON.Vector3.Distance(bonePos, target);
  76174. if (this._maxReach > 0) {
  76175. c = Math.min(this._maxReach, c);
  76176. }
  76177. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  76178. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  76179. if (acosa > 1) {
  76180. acosa = 1;
  76181. }
  76182. if (acosb > 1) {
  76183. acosb = 1;
  76184. }
  76185. if (acosa < -1) {
  76186. acosa = -1;
  76187. }
  76188. if (acosb < -1) {
  76189. acosb = -1;
  76190. }
  76191. var angA = Math.acos(acosa);
  76192. var angB = Math.acos(acosb);
  76193. var angC = -angA - angB;
  76194. if (this._rightHandedSystem) {
  76195. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  76196. mat2.multiplyToRef(mat1, mat1);
  76197. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  76198. mat2.multiplyToRef(mat1, mat1);
  76199. }
  76200. else {
  76201. var _tmpVec = BoneIKController._tmpVecs[5];
  76202. _tmpVec.copyFrom(this._bendAxis);
  76203. _tmpVec.x *= -1;
  76204. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  76205. mat2.multiplyToRef(mat1, mat1);
  76206. }
  76207. if (this.poleAngle) {
  76208. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  76209. mat1.multiplyToRef(mat2, mat1);
  76210. }
  76211. if (this._bone1) {
  76212. if (this.slerpAmount < 1) {
  76213. if (!this._slerping) {
  76214. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  76215. }
  76216. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  76217. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  76218. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  76219. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  76220. this._slerping = true;
  76221. }
  76222. else {
  76223. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  76224. this._bone1Mat.copyFrom(mat1);
  76225. this._slerping = false;
  76226. }
  76227. }
  76228. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  76229. this._bone2Ang = angC;
  76230. };
  76231. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76232. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  76233. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  76234. return BoneIKController;
  76235. }());
  76236. BABYLON.BoneIKController = BoneIKController;
  76237. })(BABYLON || (BABYLON = {}));
  76238. //# sourceMappingURL=babylon.boneIKController.js.map
  76239. "use strict";
  76240. var BABYLON;
  76241. (function (BABYLON) {
  76242. var BoneLookController = /** @class */ (function () {
  76243. /**
  76244. * Create a BoneLookController
  76245. * @param mesh the mesh that the bone belongs to
  76246. * @param bone the bone that will be looking to the target
  76247. * @param target the target Vector3 to look at
  76248. * @param settings optional settings:
  76249. * - maxYaw: the maximum angle the bone will yaw to
  76250. * - minYaw: the minimum angle the bone will yaw to
  76251. * - maxPitch: the maximum angle the bone will pitch to
  76252. * - minPitch: the minimum angle the bone will yaw to
  76253. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  76254. * - upAxis: the up axis of the coordinate system
  76255. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  76256. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  76257. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  76258. * - adjustYaw: used to make an adjustment to the yaw of the bone
  76259. * - adjustPitch: used to make an adjustment to the pitch of the bone
  76260. * - adjustRoll: used to make an adjustment to the roll of the bone
  76261. **/
  76262. function BoneLookController(mesh, bone, target, options) {
  76263. /**
  76264. * The up axis of the coordinate system that is used when the bone is rotated.
  76265. */
  76266. this.upAxis = BABYLON.Vector3.Up();
  76267. /**
  76268. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  76269. */
  76270. this.upAxisSpace = BABYLON.Space.LOCAL;
  76271. /**
  76272. * Used to make an adjustment to the yaw of the bone.
  76273. */
  76274. this.adjustYaw = 0;
  76275. /**
  76276. * Used to make an adjustment to the pitch of the bone.
  76277. */
  76278. this.adjustPitch = 0;
  76279. /**
  76280. * Used to make an adjustment to the roll of the bone.
  76281. */
  76282. this.adjustRoll = 0;
  76283. /**
  76284. * 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).
  76285. */
  76286. this.slerpAmount = 1;
  76287. this._boneQuat = BABYLON.Quaternion.Identity();
  76288. this._slerping = false;
  76289. this._firstFrameSkipped = false;
  76290. this._fowardAxis = BABYLON.Vector3.Forward();
  76291. this.mesh = mesh;
  76292. this.bone = bone;
  76293. this.target = target;
  76294. if (options) {
  76295. if (options.adjustYaw) {
  76296. this.adjustYaw = options.adjustYaw;
  76297. }
  76298. if (options.adjustPitch) {
  76299. this.adjustPitch = options.adjustPitch;
  76300. }
  76301. if (options.adjustRoll) {
  76302. this.adjustRoll = options.adjustRoll;
  76303. }
  76304. if (options.maxYaw != null) {
  76305. this.maxYaw = options.maxYaw;
  76306. }
  76307. else {
  76308. this.maxYaw = Math.PI;
  76309. }
  76310. if (options.minYaw != null) {
  76311. this.minYaw = options.minYaw;
  76312. }
  76313. else {
  76314. this.minYaw = -Math.PI;
  76315. }
  76316. if (options.maxPitch != null) {
  76317. this.maxPitch = options.maxPitch;
  76318. }
  76319. else {
  76320. this.maxPitch = Math.PI;
  76321. }
  76322. if (options.minPitch != null) {
  76323. this.minPitch = options.minPitch;
  76324. }
  76325. else {
  76326. this.minPitch = -Math.PI;
  76327. }
  76328. if (options.slerpAmount != null) {
  76329. this.slerpAmount = options.slerpAmount;
  76330. }
  76331. if (options.upAxis != null) {
  76332. this.upAxis = options.upAxis;
  76333. }
  76334. if (options.upAxisSpace != null) {
  76335. this.upAxisSpace = options.upAxisSpace;
  76336. }
  76337. if (options.yawAxis != null || options.pitchAxis != null) {
  76338. var newYawAxis = BABYLON.Axis.Y;
  76339. var newPitchAxis = BABYLON.Axis.X;
  76340. if (options.yawAxis != null) {
  76341. newYawAxis = options.yawAxis.clone();
  76342. newYawAxis.normalize();
  76343. }
  76344. if (options.pitchAxis != null) {
  76345. newPitchAxis = options.pitchAxis.clone();
  76346. newPitchAxis.normalize();
  76347. }
  76348. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  76349. this._transformYawPitch = BABYLON.Matrix.Identity();
  76350. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  76351. this._transformYawPitchInv = this._transformYawPitch.clone();
  76352. this._transformYawPitch.invert();
  76353. }
  76354. }
  76355. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  76356. this.upAxisSpace = BABYLON.Space.LOCAL;
  76357. }
  76358. }
  76359. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  76360. /**
  76361. * Get/set the minimum yaw angle that the bone can look to.
  76362. */
  76363. get: function () {
  76364. return this._minYaw;
  76365. },
  76366. set: function (value) {
  76367. this._minYaw = value;
  76368. this._minYawSin = Math.sin(value);
  76369. this._minYawCos = Math.cos(value);
  76370. if (this._maxYaw != null) {
  76371. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  76372. this._yawRange = this._maxYaw - this._minYaw;
  76373. }
  76374. },
  76375. enumerable: true,
  76376. configurable: true
  76377. });
  76378. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  76379. /**
  76380. * Get/set the maximum yaw angle that the bone can look to.
  76381. */
  76382. get: function () {
  76383. return this._maxYaw;
  76384. },
  76385. set: function (value) {
  76386. this._maxYaw = value;
  76387. this._maxYawSin = Math.sin(value);
  76388. this._maxYawCos = Math.cos(value);
  76389. if (this._minYaw != null) {
  76390. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  76391. this._yawRange = this._maxYaw - this._minYaw;
  76392. }
  76393. },
  76394. enumerable: true,
  76395. configurable: true
  76396. });
  76397. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  76398. /**
  76399. * Get/set the minimum pitch angle that the bone can look to.
  76400. */
  76401. get: function () {
  76402. return this._minPitch;
  76403. },
  76404. set: function (value) {
  76405. this._minPitch = value;
  76406. this._minPitchTan = Math.tan(value);
  76407. },
  76408. enumerable: true,
  76409. configurable: true
  76410. });
  76411. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  76412. /**
  76413. * Get/set the maximum pitch angle that the bone can look to.
  76414. */
  76415. get: function () {
  76416. return this._maxPitch;
  76417. },
  76418. set: function (value) {
  76419. this._maxPitch = value;
  76420. this._maxPitchTan = Math.tan(value);
  76421. },
  76422. enumerable: true,
  76423. configurable: true
  76424. });
  76425. /**
  76426. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  76427. */
  76428. BoneLookController.prototype.update = function () {
  76429. //skip the first frame when slerping so that the mesh rotation is correct
  76430. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  76431. this._firstFrameSkipped = true;
  76432. return;
  76433. }
  76434. var bone = this.bone;
  76435. var bonePos = BoneLookController._tmpVecs[0];
  76436. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  76437. var target = this.target;
  76438. var _tmpMat1 = BoneLookController._tmpMats[0];
  76439. var _tmpMat2 = BoneLookController._tmpMats[1];
  76440. var mesh = this.mesh;
  76441. var parentBone = bone.getParent();
  76442. var upAxis = BoneLookController._tmpVecs[1];
  76443. upAxis.copyFrom(this.upAxis);
  76444. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  76445. if (this._transformYawPitch) {
  76446. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  76447. }
  76448. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  76449. }
  76450. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  76451. mesh.getDirectionToRef(upAxis, upAxis);
  76452. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  76453. upAxis.normalize();
  76454. }
  76455. }
  76456. var checkYaw = false;
  76457. var checkPitch = false;
  76458. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  76459. checkYaw = true;
  76460. }
  76461. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  76462. checkPitch = true;
  76463. }
  76464. if (checkYaw || checkPitch) {
  76465. var spaceMat = BoneLookController._tmpMats[2];
  76466. var spaceMatInv = BoneLookController._tmpMats[3];
  76467. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  76468. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  76469. }
  76470. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  76471. spaceMat.copyFrom(mesh.getWorldMatrix());
  76472. }
  76473. else {
  76474. var forwardAxis = BoneLookController._tmpVecs[2];
  76475. forwardAxis.copyFrom(this._fowardAxis);
  76476. if (this._transformYawPitch) {
  76477. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  76478. }
  76479. if (parentBone) {
  76480. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  76481. }
  76482. else {
  76483. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  76484. }
  76485. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  76486. rightAxis.normalize();
  76487. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  76488. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  76489. }
  76490. spaceMat.invertToRef(spaceMatInv);
  76491. var xzlen = null;
  76492. if (checkPitch) {
  76493. var localTarget = BoneLookController._tmpVecs[3];
  76494. target.subtractToRef(bonePos, localTarget);
  76495. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  76496. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  76497. var pitch = Math.atan2(localTarget.y, xzlen);
  76498. var newPitch = pitch;
  76499. if (pitch > this._maxPitch) {
  76500. localTarget.y = this._maxPitchTan * xzlen;
  76501. newPitch = this._maxPitch;
  76502. }
  76503. else if (pitch < this._minPitch) {
  76504. localTarget.y = this._minPitchTan * xzlen;
  76505. newPitch = this._minPitch;
  76506. }
  76507. if (pitch != newPitch) {
  76508. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  76509. localTarget.addInPlace(bonePos);
  76510. target = localTarget;
  76511. }
  76512. }
  76513. if (checkYaw) {
  76514. var localTarget = BoneLookController._tmpVecs[4];
  76515. target.subtractToRef(bonePos, localTarget);
  76516. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  76517. var yaw = Math.atan2(localTarget.x, localTarget.z);
  76518. var newYaw = yaw;
  76519. if (yaw > this._maxYaw || yaw < this._minYaw) {
  76520. if (xzlen == null) {
  76521. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  76522. }
  76523. if (this._yawRange > Math.PI) {
  76524. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  76525. localTarget.z = this._maxYawCos * xzlen;
  76526. localTarget.x = this._maxYawSin * xzlen;
  76527. newYaw = this._maxYaw;
  76528. }
  76529. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  76530. localTarget.z = this._minYawCos * xzlen;
  76531. localTarget.x = this._minYawSin * xzlen;
  76532. newYaw = this._minYaw;
  76533. }
  76534. }
  76535. else {
  76536. if (yaw > this._maxYaw) {
  76537. localTarget.z = this._maxYawCos * xzlen;
  76538. localTarget.x = this._maxYawSin * xzlen;
  76539. newYaw = this._maxYaw;
  76540. }
  76541. else if (yaw < this._minYaw) {
  76542. localTarget.z = this._minYawCos * xzlen;
  76543. localTarget.x = this._minYawSin * xzlen;
  76544. newYaw = this._minYaw;
  76545. }
  76546. }
  76547. }
  76548. if (this._slerping && this._yawRange > Math.PI) {
  76549. //are we going to be crossing into the min/max region?
  76550. var boneFwd = BoneLookController._tmpVecs[8];
  76551. boneFwd.copyFrom(BABYLON.Axis.Z);
  76552. if (this._transformYawPitch) {
  76553. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  76554. }
  76555. var boneRotMat = BoneLookController._tmpMats[4];
  76556. this._boneQuat.toRotationMatrix(boneRotMat);
  76557. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  76558. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  76559. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  76560. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  76561. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  76562. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  76563. if (angBtwTar > angBtwMidYaw) {
  76564. if (xzlen == null) {
  76565. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  76566. }
  76567. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  76568. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  76569. if (angBtwMin < angBtwMax) {
  76570. newYaw = boneYaw + Math.PI * .75;
  76571. localTarget.z = Math.cos(newYaw) * xzlen;
  76572. localTarget.x = Math.sin(newYaw) * xzlen;
  76573. }
  76574. else {
  76575. newYaw = boneYaw - Math.PI * .75;
  76576. localTarget.z = Math.cos(newYaw) * xzlen;
  76577. localTarget.x = Math.sin(newYaw) * xzlen;
  76578. }
  76579. }
  76580. }
  76581. if (yaw != newYaw) {
  76582. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  76583. localTarget.addInPlace(bonePos);
  76584. target = localTarget;
  76585. }
  76586. }
  76587. }
  76588. var zaxis = BoneLookController._tmpVecs[5];
  76589. var xaxis = BoneLookController._tmpVecs[6];
  76590. var yaxis = BoneLookController._tmpVecs[7];
  76591. var _tmpQuat = BoneLookController._tmpQuat;
  76592. target.subtractToRef(bonePos, zaxis);
  76593. zaxis.normalize();
  76594. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  76595. xaxis.normalize();
  76596. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  76597. yaxis.normalize();
  76598. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  76599. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  76600. return;
  76601. }
  76602. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  76603. return;
  76604. }
  76605. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  76606. return;
  76607. }
  76608. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  76609. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  76610. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  76611. }
  76612. if (this.slerpAmount < 1) {
  76613. if (!this._slerping) {
  76614. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  76615. }
  76616. if (this._transformYawPitch) {
  76617. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  76618. }
  76619. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  76620. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  76621. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  76622. this._slerping = true;
  76623. }
  76624. else {
  76625. if (this._transformYawPitch) {
  76626. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  76627. }
  76628. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  76629. this._slerping = false;
  76630. }
  76631. };
  76632. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  76633. var angDiff = ang2 - ang1;
  76634. angDiff %= Math.PI * 2;
  76635. if (angDiff > Math.PI) {
  76636. angDiff -= Math.PI * 2;
  76637. }
  76638. else if (angDiff < -Math.PI) {
  76639. angDiff += Math.PI * 2;
  76640. }
  76641. return angDiff;
  76642. };
  76643. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  76644. ang1 %= (2 * Math.PI);
  76645. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  76646. ang2 %= (2 * Math.PI);
  76647. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  76648. var ab = 0;
  76649. if (ang1 < ang2) {
  76650. ab = ang2 - ang1;
  76651. }
  76652. else {
  76653. ab = ang1 - ang2;
  76654. }
  76655. if (ab > Math.PI) {
  76656. ab = Math.PI * 2 - ab;
  76657. }
  76658. return ab;
  76659. };
  76660. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  76661. ang %= (2 * Math.PI);
  76662. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  76663. ang1 %= (2 * Math.PI);
  76664. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  76665. ang2 %= (2 * Math.PI);
  76666. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  76667. if (ang1 < ang2) {
  76668. if (ang > ang1 && ang < ang2) {
  76669. return true;
  76670. }
  76671. }
  76672. else {
  76673. if (ang > ang2 && ang < ang1) {
  76674. return true;
  76675. }
  76676. }
  76677. return false;
  76678. };
  76679. 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()];
  76680. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  76681. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  76682. return BoneLookController;
  76683. }());
  76684. BABYLON.BoneLookController = BoneLookController;
  76685. })(BABYLON || (BABYLON = {}));
  76686. //# sourceMappingURL=babylon.boneLookController.js.map
  76687. "use strict";
  76688. var BABYLON;
  76689. (function (BABYLON) {
  76690. var Skeleton = /** @class */ (function () {
  76691. function Skeleton(name, id, scene) {
  76692. this.name = name;
  76693. this.id = id;
  76694. this.bones = new Array();
  76695. this.needInitialSkinMatrix = false;
  76696. this._isDirty = true;
  76697. this._meshesWithPoseMatrix = new Array();
  76698. this._identity = BABYLON.Matrix.Identity();
  76699. this._ranges = {};
  76700. this._lastAbsoluteTransformsUpdateId = -1;
  76701. /**
  76702. * Specifies if the skeleton should be serialized.
  76703. */
  76704. this.doNotSerialize = false;
  76705. // Events
  76706. /**
  76707. * An event triggered before computing the skeleton's matrices
  76708. */
  76709. this.onBeforeComputeObservable = new BABYLON.Observable();
  76710. this.bones = [];
  76711. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  76712. scene.skeletons.push(this);
  76713. //make sure it will recalculate the matrix next time prepare is called.
  76714. this._isDirty = true;
  76715. }
  76716. // Members
  76717. Skeleton.prototype.getTransformMatrices = function (mesh) {
  76718. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  76719. return mesh._bonesTransformMatrices;
  76720. }
  76721. if (!this._transformMatrices) {
  76722. this.prepare();
  76723. }
  76724. return this._transformMatrices;
  76725. };
  76726. Skeleton.prototype.getScene = function () {
  76727. return this._scene;
  76728. };
  76729. // Methods
  76730. /**
  76731. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  76732. */
  76733. Skeleton.prototype.toString = function (fullDetails) {
  76734. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  76735. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  76736. if (fullDetails) {
  76737. ret += ", Ranges: {";
  76738. var first = true;
  76739. for (var name_1 in this._ranges) {
  76740. if (first) {
  76741. ret += ", ";
  76742. first = false;
  76743. }
  76744. ret += name_1;
  76745. }
  76746. ret += "}";
  76747. }
  76748. return ret;
  76749. };
  76750. /**
  76751. * Get bone's index searching by name
  76752. * @param {string} name is bone's name to search for
  76753. * @return {number} Indice of the bone. Returns -1 if not found
  76754. */
  76755. Skeleton.prototype.getBoneIndexByName = function (name) {
  76756. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  76757. if (this.bones[boneIndex].name === name) {
  76758. return boneIndex;
  76759. }
  76760. }
  76761. return -1;
  76762. };
  76763. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  76764. // check name not already in use
  76765. if (!this._ranges[name]) {
  76766. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  76767. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  76768. if (this.bones[i].animations[0]) {
  76769. this.bones[i].animations[0].createRange(name, from, to);
  76770. }
  76771. }
  76772. }
  76773. };
  76774. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  76775. if (deleteFrames === void 0) { deleteFrames = true; }
  76776. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  76777. if (this.bones[i].animations[0]) {
  76778. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  76779. }
  76780. }
  76781. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  76782. };
  76783. Skeleton.prototype.getAnimationRange = function (name) {
  76784. return this._ranges[name];
  76785. };
  76786. /**
  76787. * Returns as an Array, all AnimationRanges defined on this skeleton
  76788. */
  76789. Skeleton.prototype.getAnimationRanges = function () {
  76790. var animationRanges = [];
  76791. var name;
  76792. var i = 0;
  76793. for (name in this._ranges) {
  76794. animationRanges[i] = this._ranges[name];
  76795. i++;
  76796. }
  76797. return animationRanges;
  76798. };
  76799. /**
  76800. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  76801. */
  76802. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  76803. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  76804. if (this._ranges[name] || !source.getAnimationRange(name)) {
  76805. return false;
  76806. }
  76807. var ret = true;
  76808. var frameOffset = this._getHighestAnimationFrame() + 1;
  76809. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  76810. var boneDict = {};
  76811. var sourceBones = source.bones;
  76812. var nBones;
  76813. var i;
  76814. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  76815. boneDict[sourceBones[i].name] = sourceBones[i];
  76816. }
  76817. if (this.bones.length !== sourceBones.length) {
  76818. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  76819. ret = false;
  76820. }
  76821. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  76822. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  76823. var boneName = this.bones[i].name;
  76824. var sourceBone = boneDict[boneName];
  76825. if (sourceBone) {
  76826. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  76827. }
  76828. else {
  76829. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  76830. ret = false;
  76831. }
  76832. }
  76833. // do not call createAnimationRange(), since it also is done to bones, which was already done
  76834. var range = source.getAnimationRange(name);
  76835. if (range) {
  76836. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  76837. }
  76838. return ret;
  76839. };
  76840. Skeleton.prototype.returnToRest = function () {
  76841. for (var index = 0; index < this.bones.length; index++) {
  76842. this.bones[index].returnToRest();
  76843. }
  76844. };
  76845. Skeleton.prototype._getHighestAnimationFrame = function () {
  76846. var ret = 0;
  76847. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  76848. if (this.bones[i].animations[0]) {
  76849. var highest = this.bones[i].animations[0].getHighestFrame();
  76850. if (ret < highest) {
  76851. ret = highest;
  76852. }
  76853. }
  76854. }
  76855. return ret;
  76856. };
  76857. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  76858. var range = this.getAnimationRange(name);
  76859. if (!range) {
  76860. return null;
  76861. }
  76862. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  76863. };
  76864. Skeleton.prototype._markAsDirty = function () {
  76865. this._isDirty = true;
  76866. };
  76867. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  76868. this._meshesWithPoseMatrix.push(mesh);
  76869. };
  76870. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  76871. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  76872. if (index > -1) {
  76873. this._meshesWithPoseMatrix.splice(index, 1);
  76874. }
  76875. };
  76876. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  76877. this.onBeforeComputeObservable.notifyObservers(this);
  76878. for (var index = 0; index < this.bones.length; index++) {
  76879. var bone = this.bones[index];
  76880. var parentBone = bone.getParent();
  76881. if (parentBone) {
  76882. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  76883. }
  76884. else {
  76885. if (initialSkinMatrix) {
  76886. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  76887. }
  76888. else {
  76889. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  76890. }
  76891. }
  76892. if (bone._index !== -1) {
  76893. var mappedIndex = bone._index === null ? index : bone._index;
  76894. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  76895. }
  76896. }
  76897. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  76898. };
  76899. Skeleton.prototype.prepare = function () {
  76900. if (!this._isDirty) {
  76901. return;
  76902. }
  76903. if (this.needInitialSkinMatrix) {
  76904. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  76905. var mesh = this._meshesWithPoseMatrix[index];
  76906. var poseMatrix = mesh.getPoseMatrix();
  76907. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  76908. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  76909. }
  76910. if (this._synchronizedWithMesh !== mesh) {
  76911. this._synchronizedWithMesh = mesh;
  76912. // Prepare bones
  76913. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  76914. var bone = this.bones[boneIndex];
  76915. if (!bone.getParent()) {
  76916. var matrix = bone.getBaseMatrix();
  76917. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  76918. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  76919. }
  76920. }
  76921. }
  76922. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  76923. }
  76924. }
  76925. else {
  76926. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  76927. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  76928. }
  76929. this._computeTransformMatrices(this._transformMatrices, null);
  76930. }
  76931. this._isDirty = false;
  76932. this._scene._activeBones.addCount(this.bones.length, false);
  76933. };
  76934. Skeleton.prototype.getAnimatables = function () {
  76935. if (!this._animatables || this._animatables.length !== this.bones.length) {
  76936. this._animatables = [];
  76937. for (var index = 0; index < this.bones.length; index++) {
  76938. this._animatables.push(this.bones[index]);
  76939. }
  76940. }
  76941. return this._animatables;
  76942. };
  76943. Skeleton.prototype.clone = function (name, id) {
  76944. var result = new Skeleton(name, id || name, this._scene);
  76945. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  76946. for (var index = 0; index < this.bones.length; index++) {
  76947. var source = this.bones[index];
  76948. var parentBone = null;
  76949. var parent_1 = source.getParent();
  76950. if (parent_1) {
  76951. var parentIndex = this.bones.indexOf(parent_1);
  76952. parentBone = result.bones[parentIndex];
  76953. }
  76954. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  76955. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  76956. }
  76957. if (this._ranges) {
  76958. result._ranges = {};
  76959. for (var rangeName in this._ranges) {
  76960. var range = this._ranges[rangeName];
  76961. if (range) {
  76962. result._ranges[rangeName] = range.clone();
  76963. }
  76964. }
  76965. }
  76966. this._isDirty = true;
  76967. return result;
  76968. };
  76969. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  76970. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  76971. this.bones.forEach(function (bone) {
  76972. bone.animations.forEach(function (animation) {
  76973. animation.enableBlending = true;
  76974. animation.blendingSpeed = blendingSpeed;
  76975. });
  76976. });
  76977. };
  76978. Skeleton.prototype.dispose = function () {
  76979. this._meshesWithPoseMatrix = [];
  76980. // Animations
  76981. this.getScene().stopAnimation(this);
  76982. // Remove from scene
  76983. this.getScene().removeSkeleton(this);
  76984. };
  76985. Skeleton.prototype.serialize = function () {
  76986. var serializationObject = {};
  76987. serializationObject.name = this.name;
  76988. serializationObject.id = this.id;
  76989. if (this.dimensionsAtRest) {
  76990. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  76991. }
  76992. serializationObject.bones = [];
  76993. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  76994. for (var index = 0; index < this.bones.length; index++) {
  76995. var bone = this.bones[index];
  76996. var parent_2 = bone.getParent();
  76997. var serializedBone = {
  76998. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  76999. name: bone.name,
  77000. matrix: bone.getBaseMatrix().toArray(),
  77001. rest: bone.getRestPose().toArray()
  77002. };
  77003. serializationObject.bones.push(serializedBone);
  77004. if (bone.length) {
  77005. serializedBone.length = bone.length;
  77006. }
  77007. if (bone.animations && bone.animations.length > 0) {
  77008. serializedBone.animation = bone.animations[0].serialize();
  77009. }
  77010. serializationObject.ranges = [];
  77011. for (var name in this._ranges) {
  77012. var source = this._ranges[name];
  77013. if (!source) {
  77014. continue;
  77015. }
  77016. var range = {};
  77017. range.name = name;
  77018. range.from = source.from;
  77019. range.to = source.to;
  77020. serializationObject.ranges.push(range);
  77021. }
  77022. }
  77023. return serializationObject;
  77024. };
  77025. Skeleton.Parse = function (parsedSkeleton, scene) {
  77026. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  77027. if (parsedSkeleton.dimensionsAtRest) {
  77028. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  77029. }
  77030. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  77031. var index;
  77032. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  77033. var parsedBone = parsedSkeleton.bones[index];
  77034. var parentBone = null;
  77035. if (parsedBone.parentBoneIndex > -1) {
  77036. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  77037. }
  77038. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  77039. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  77040. if (parsedBone.length) {
  77041. bone.length = parsedBone.length;
  77042. }
  77043. if (parsedBone.animation) {
  77044. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  77045. }
  77046. }
  77047. // placed after bones, so createAnimationRange can cascade down
  77048. if (parsedSkeleton.ranges) {
  77049. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  77050. var data = parsedSkeleton.ranges[index];
  77051. skeleton.createAnimationRange(data.name, data.from, data.to);
  77052. }
  77053. }
  77054. return skeleton;
  77055. };
  77056. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  77057. if (forceUpdate === void 0) { forceUpdate = false; }
  77058. var renderId = this._scene.getRenderId();
  77059. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  77060. this.bones[0].computeAbsoluteTransforms();
  77061. this._lastAbsoluteTransformsUpdateId = renderId;
  77062. }
  77063. };
  77064. Skeleton.prototype.getPoseMatrix = function () {
  77065. var poseMatrix = null;
  77066. if (this._meshesWithPoseMatrix.length > 0) {
  77067. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  77068. }
  77069. return poseMatrix;
  77070. };
  77071. Skeleton.prototype.sortBones = function () {
  77072. var bones = new Array();
  77073. var visited = new Array(this.bones.length);
  77074. for (var index = 0; index < this.bones.length; index++) {
  77075. this._sortBones(index, bones, visited);
  77076. }
  77077. this.bones = bones;
  77078. };
  77079. Skeleton.prototype._sortBones = function (index, bones, visited) {
  77080. if (visited[index]) {
  77081. return;
  77082. }
  77083. visited[index] = true;
  77084. var bone = this.bones[index];
  77085. if (bone._index === undefined) {
  77086. bone._index = index;
  77087. }
  77088. var parentBone = bone.getParent();
  77089. if (parentBone) {
  77090. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  77091. }
  77092. bones.push(bone);
  77093. };
  77094. return Skeleton;
  77095. }());
  77096. BABYLON.Skeleton = Skeleton;
  77097. })(BABYLON || (BABYLON = {}));
  77098. //# sourceMappingURL=babylon.skeleton.js.map
  77099. "use strict";
  77100. var BABYLON;
  77101. (function (BABYLON) {
  77102. var SphericalPolynomial = /** @class */ (function () {
  77103. function SphericalPolynomial() {
  77104. this.x = BABYLON.Vector3.Zero();
  77105. this.y = BABYLON.Vector3.Zero();
  77106. this.z = BABYLON.Vector3.Zero();
  77107. this.xx = BABYLON.Vector3.Zero();
  77108. this.yy = BABYLON.Vector3.Zero();
  77109. this.zz = BABYLON.Vector3.Zero();
  77110. this.xy = BABYLON.Vector3.Zero();
  77111. this.yz = BABYLON.Vector3.Zero();
  77112. this.zx = BABYLON.Vector3.Zero();
  77113. }
  77114. SphericalPolynomial.prototype.addAmbient = function (color) {
  77115. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  77116. this.xx = this.xx.add(colorVector);
  77117. this.yy = this.yy.add(colorVector);
  77118. this.zz = this.zz.add(colorVector);
  77119. };
  77120. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  77121. var result = new SphericalPolynomial();
  77122. result.x = harmonics.L11.scale(1.02333);
  77123. result.y = harmonics.L1_1.scale(1.02333);
  77124. result.z = harmonics.L10.scale(1.02333);
  77125. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  77126. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  77127. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  77128. result.yz = harmonics.L2_1.scale(0.858086);
  77129. result.zx = harmonics.L21.scale(0.858086);
  77130. result.xy = harmonics.L2_2.scale(0.858086);
  77131. result.scale(1.0 / Math.PI);
  77132. return result;
  77133. };
  77134. SphericalPolynomial.prototype.scale = function (scale) {
  77135. this.x = this.x.scale(scale);
  77136. this.y = this.y.scale(scale);
  77137. this.z = this.z.scale(scale);
  77138. this.xx = this.xx.scale(scale);
  77139. this.yy = this.yy.scale(scale);
  77140. this.zz = this.zz.scale(scale);
  77141. this.yz = this.yz.scale(scale);
  77142. this.zx = this.zx.scale(scale);
  77143. this.xy = this.xy.scale(scale);
  77144. };
  77145. return SphericalPolynomial;
  77146. }());
  77147. BABYLON.SphericalPolynomial = SphericalPolynomial;
  77148. var SphericalHarmonics = /** @class */ (function () {
  77149. function SphericalHarmonics() {
  77150. this.L00 = BABYLON.Vector3.Zero();
  77151. this.L1_1 = BABYLON.Vector3.Zero();
  77152. this.L10 = BABYLON.Vector3.Zero();
  77153. this.L11 = BABYLON.Vector3.Zero();
  77154. this.L2_2 = BABYLON.Vector3.Zero();
  77155. this.L2_1 = BABYLON.Vector3.Zero();
  77156. this.L20 = BABYLON.Vector3.Zero();
  77157. this.L21 = BABYLON.Vector3.Zero();
  77158. this.L22 = BABYLON.Vector3.Zero();
  77159. }
  77160. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  77161. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  77162. var c = colorVector.scale(deltaSolidAngle);
  77163. this.L00 = this.L00.add(c.scale(0.282095));
  77164. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  77165. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  77166. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  77167. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  77168. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  77169. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  77170. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  77171. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  77172. };
  77173. SphericalHarmonics.prototype.scale = function (scale) {
  77174. this.L00 = this.L00.scale(scale);
  77175. this.L1_1 = this.L1_1.scale(scale);
  77176. this.L10 = this.L10.scale(scale);
  77177. this.L11 = this.L11.scale(scale);
  77178. this.L2_2 = this.L2_2.scale(scale);
  77179. this.L2_1 = this.L2_1.scale(scale);
  77180. this.L20 = this.L20.scale(scale);
  77181. this.L21 = this.L21.scale(scale);
  77182. this.L22 = this.L22.scale(scale);
  77183. };
  77184. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  77185. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  77186. //
  77187. // E_lm = A_l * L_lm
  77188. //
  77189. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  77190. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  77191. // the scaling factors are given in equation 9.
  77192. // Constant (Band 0)
  77193. this.L00 = this.L00.scale(3.141593);
  77194. // Linear (Band 1)
  77195. this.L1_1 = this.L1_1.scale(2.094395);
  77196. this.L10 = this.L10.scale(2.094395);
  77197. this.L11 = this.L11.scale(2.094395);
  77198. // Quadratic (Band 2)
  77199. this.L2_2 = this.L2_2.scale(0.785398);
  77200. this.L2_1 = this.L2_1.scale(0.785398);
  77201. this.L20 = this.L20.scale(0.785398);
  77202. this.L21 = this.L21.scale(0.785398);
  77203. this.L22 = this.L22.scale(0.785398);
  77204. };
  77205. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  77206. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  77207. // L = (1/pi) * E * rho
  77208. //
  77209. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  77210. this.scale(1.0 / Math.PI);
  77211. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  77212. // (The pixel shader must apply albedo after texture fetches, etc).
  77213. };
  77214. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  77215. var result = new SphericalHarmonics();
  77216. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  77217. result.L1_1 = polynomial.y.scale(0.977204);
  77218. result.L10 = polynomial.z.scale(0.977204);
  77219. result.L11 = polynomial.x.scale(0.977204);
  77220. result.L2_2 = polynomial.xy.scale(1.16538);
  77221. result.L2_1 = polynomial.yz.scale(1.16538);
  77222. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  77223. result.L21 = polynomial.zx.scale(1.16538);
  77224. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  77225. result.scale(Math.PI);
  77226. return result;
  77227. };
  77228. return SphericalHarmonics;
  77229. }());
  77230. BABYLON.SphericalHarmonics = SphericalHarmonics;
  77231. })(BABYLON || (BABYLON = {}));
  77232. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  77233. "use strict";
  77234. var BABYLON;
  77235. (function (BABYLON) {
  77236. var FileFaceOrientation = /** @class */ (function () {
  77237. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  77238. this.name = name;
  77239. this.worldAxisForNormal = worldAxisForNormal;
  77240. this.worldAxisForFileX = worldAxisForFileX;
  77241. this.worldAxisForFileY = worldAxisForFileY;
  77242. }
  77243. return FileFaceOrientation;
  77244. }());
  77245. ;
  77246. /**
  77247. * Helper class dealing with the extraction of spherical polynomial dataArray
  77248. * from a cube map.
  77249. */
  77250. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  77251. function CubeMapToSphericalPolynomialTools() {
  77252. }
  77253. /**
  77254. * Converts a texture to the according Spherical Polynomial data.
  77255. * This extracts the first 3 orders only as they are the only one used in the lighting.
  77256. *
  77257. * @param texture The texture to extract the information from.
  77258. * @return The Spherical Polynomial data.
  77259. */
  77260. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  77261. if (!texture.isCube) {
  77262. // Only supports cube Textures currently.
  77263. return null;
  77264. }
  77265. var size = texture.getSize().width;
  77266. var right = texture.readPixels(0);
  77267. var left = texture.readPixels(1);
  77268. var up;
  77269. var down;
  77270. if (texture.isRenderTarget) {
  77271. up = texture.readPixels(3);
  77272. down = texture.readPixels(2);
  77273. }
  77274. else {
  77275. up = texture.readPixels(2);
  77276. down = texture.readPixels(3);
  77277. }
  77278. var front = texture.readPixels(4);
  77279. var back = texture.readPixels(5);
  77280. var gammaSpace = texture.gammaSpace;
  77281. // Always read as RGBA.
  77282. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  77283. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  77284. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  77285. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  77286. }
  77287. var cubeInfo = {
  77288. size: size,
  77289. right: right,
  77290. left: left,
  77291. up: up,
  77292. down: down,
  77293. front: front,
  77294. back: back,
  77295. format: format,
  77296. type: type,
  77297. gammaSpace: gammaSpace,
  77298. };
  77299. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  77300. };
  77301. /**
  77302. * Converts a cubemap to the according Spherical Polynomial data.
  77303. * This extracts the first 3 orders only as they are the only one used in the lighting.
  77304. *
  77305. * @param cubeInfo The Cube map to extract the information from.
  77306. * @return The Spherical Polynomial data.
  77307. */
  77308. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  77309. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  77310. var totalSolidAngle = 0.0;
  77311. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  77312. var du = 2.0 / cubeInfo.size;
  77313. var dv = du;
  77314. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  77315. var minUV = du * 0.5 - 1.0;
  77316. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  77317. var fileFace = this.FileFaces[faceIndex];
  77318. var dataArray = cubeInfo[fileFace.name];
  77319. var v = minUV;
  77320. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  77321. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  77322. // Because SP is still linear, so summation is fine in that basis.
  77323. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  77324. for (var y = 0; y < cubeInfo.size; y++) {
  77325. var u = minUV;
  77326. for (var x = 0; x < cubeInfo.size; x++) {
  77327. // World direction (not normalised)
  77328. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  77329. worldDirection.normalize();
  77330. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  77331. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  77332. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  77333. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  77334. // Handle Integer types.
  77335. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  77336. r /= 255;
  77337. g /= 255;
  77338. b /= 255;
  77339. }
  77340. // Handle Gamma space textures.
  77341. if (cubeInfo.gammaSpace) {
  77342. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  77343. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  77344. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  77345. }
  77346. var color = new BABYLON.Color3(r, g, b);
  77347. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  77348. totalSolidAngle += deltaSolidAngle;
  77349. u += du;
  77350. }
  77351. v += dv;
  77352. }
  77353. }
  77354. // Solid angle for entire sphere is 4*pi
  77355. var sphereSolidAngle = 4.0 * Math.PI;
  77356. // Adjust the solid angle to allow for how many faces we processed.
  77357. var facesProcessed = 6.0;
  77358. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  77359. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  77360. // This is needed because the numerical integration over the cube uses a
  77361. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  77362. // and also to compensate for accumulative error due to float precision in the summation.
  77363. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  77364. sphericalHarmonics.scale(correctionFactor);
  77365. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  77366. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  77367. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  77368. };
  77369. CubeMapToSphericalPolynomialTools.FileFaces = [
  77370. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  77371. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  77372. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  77373. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  77374. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  77375. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  77376. ];
  77377. return CubeMapToSphericalPolynomialTools;
  77378. }());
  77379. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  77380. })(BABYLON || (BABYLON = {}));
  77381. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  77382. "use strict";
  77383. var BABYLON;
  77384. (function (BABYLON) {
  77385. /**
  77386. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  77387. */
  77388. var PanoramaToCubeMapTools = /** @class */ (function () {
  77389. function PanoramaToCubeMapTools() {
  77390. }
  77391. /**
  77392. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  77393. *
  77394. * @param float32Array The source data.
  77395. * @param inputWidth The width of the input panorama.
  77396. * @param inputhHeight The height of the input panorama.
  77397. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  77398. * @return The cubemap data
  77399. */
  77400. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  77401. if (!float32Array) {
  77402. throw "ConvertPanoramaToCubemap: input cannot be null";
  77403. }
  77404. if (float32Array.length != inputWidth * inputHeight * 3) {
  77405. throw "ConvertPanoramaToCubemap: input size is wrong";
  77406. }
  77407. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  77408. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  77409. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  77410. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  77411. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  77412. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  77413. return {
  77414. front: textureFront,
  77415. back: textureBack,
  77416. left: textureLeft,
  77417. right: textureRight,
  77418. up: textureUp,
  77419. down: textureDown,
  77420. size: size,
  77421. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  77422. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  77423. gammaSpace: false,
  77424. };
  77425. };
  77426. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  77427. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  77428. var textureArray = new Float32Array(buffer);
  77429. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  77430. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  77431. var dy = 1 / texSize;
  77432. var fy = 0;
  77433. for (var y = 0; y < texSize; y++) {
  77434. var xv1 = faceData[0];
  77435. var xv2 = faceData[2];
  77436. for (var x = 0; x < texSize; x++) {
  77437. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  77438. v.normalize();
  77439. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  77440. // 3 channels per pixels
  77441. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  77442. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  77443. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  77444. xv1 = xv1.add(rotDX1);
  77445. xv2 = xv2.add(rotDX2);
  77446. }
  77447. fy += dy;
  77448. }
  77449. return textureArray;
  77450. };
  77451. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  77452. var theta = Math.atan2(vDir.z, vDir.x);
  77453. var phi = Math.acos(vDir.y);
  77454. while (theta < -Math.PI)
  77455. theta += 2 * Math.PI;
  77456. while (theta > Math.PI)
  77457. theta -= 2 * Math.PI;
  77458. var dx = theta / Math.PI;
  77459. var dy = phi / Math.PI;
  77460. // recenter.
  77461. dx = dx * 0.5 + 0.5;
  77462. var px = Math.round(dx * inputWidth);
  77463. if (px < 0)
  77464. px = 0;
  77465. else if (px >= inputWidth)
  77466. px = inputWidth - 1;
  77467. var py = Math.round(dy * inputHeight);
  77468. if (py < 0)
  77469. py = 0;
  77470. else if (py >= inputHeight)
  77471. py = inputHeight - 1;
  77472. var inputY = (inputHeight - py - 1);
  77473. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  77474. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  77475. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  77476. return {
  77477. r: r,
  77478. g: g,
  77479. b: b
  77480. };
  77481. };
  77482. PanoramaToCubeMapTools.FACE_FRONT = [
  77483. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  77484. new BABYLON.Vector3(1.0, -1.0, -1.0),
  77485. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  77486. new BABYLON.Vector3(1.0, 1.0, -1.0)
  77487. ];
  77488. PanoramaToCubeMapTools.FACE_BACK = [
  77489. new BABYLON.Vector3(1.0, -1.0, 1.0),
  77490. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  77491. new BABYLON.Vector3(1.0, 1.0, 1.0),
  77492. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  77493. ];
  77494. PanoramaToCubeMapTools.FACE_RIGHT = [
  77495. new BABYLON.Vector3(1.0, -1.0, -1.0),
  77496. new BABYLON.Vector3(1.0, -1.0, 1.0),
  77497. new BABYLON.Vector3(1.0, 1.0, -1.0),
  77498. new BABYLON.Vector3(1.0, 1.0, 1.0)
  77499. ];
  77500. PanoramaToCubeMapTools.FACE_LEFT = [
  77501. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  77502. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  77503. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  77504. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  77505. ];
  77506. PanoramaToCubeMapTools.FACE_DOWN = [
  77507. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  77508. new BABYLON.Vector3(1.0, 1.0, -1.0),
  77509. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  77510. new BABYLON.Vector3(1.0, 1.0, 1.0)
  77511. ];
  77512. PanoramaToCubeMapTools.FACE_UP = [
  77513. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  77514. new BABYLON.Vector3(1.0, -1.0, 1.0),
  77515. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  77516. new BABYLON.Vector3(1.0, -1.0, -1.0)
  77517. ];
  77518. return PanoramaToCubeMapTools;
  77519. }());
  77520. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  77521. })(BABYLON || (BABYLON = {}));
  77522. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  77523. "use strict";
  77524. var BABYLON;
  77525. (function (BABYLON) {
  77526. ;
  77527. /**
  77528. * This groups tools to convert HDR texture to native colors array.
  77529. */
  77530. var HDRTools = /** @class */ (function () {
  77531. function HDRTools() {
  77532. }
  77533. HDRTools.Ldexp = function (mantissa, exponent) {
  77534. if (exponent > 1023) {
  77535. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  77536. }
  77537. if (exponent < -1074) {
  77538. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  77539. }
  77540. return mantissa * Math.pow(2, exponent);
  77541. };
  77542. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  77543. if (exponent > 0) {
  77544. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  77545. float32array[index + 0] = red * exponent;
  77546. float32array[index + 1] = green * exponent;
  77547. float32array[index + 2] = blue * exponent;
  77548. }
  77549. else {
  77550. float32array[index + 0] = 0;
  77551. float32array[index + 1] = 0;
  77552. float32array[index + 2] = 0;
  77553. }
  77554. };
  77555. HDRTools.readStringLine = function (uint8array, startIndex) {
  77556. var line = "";
  77557. var character = "";
  77558. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  77559. character = String.fromCharCode(uint8array[i]);
  77560. if (character == "\n") {
  77561. break;
  77562. }
  77563. line += character;
  77564. }
  77565. return line;
  77566. };
  77567. /**
  77568. * Reads header information from an RGBE texture stored in a native array.
  77569. * More information on this format are available here:
  77570. * https://en.wikipedia.org/wiki/RGBE_image_format
  77571. *
  77572. * @param uint8array The binary file stored in native array.
  77573. * @return The header information.
  77574. */
  77575. HDRTools.RGBE_ReadHeader = function (uint8array) {
  77576. var height = 0;
  77577. var width = 0;
  77578. var line = this.readStringLine(uint8array, 0);
  77579. if (line[0] != '#' || line[1] != '?') {
  77580. throw "Bad HDR Format.";
  77581. }
  77582. var endOfHeader = false;
  77583. var findFormat = false;
  77584. var lineIndex = 0;
  77585. do {
  77586. lineIndex += (line.length + 1);
  77587. line = this.readStringLine(uint8array, lineIndex);
  77588. if (line == "FORMAT=32-bit_rle_rgbe") {
  77589. findFormat = true;
  77590. }
  77591. else if (line.length == 0) {
  77592. endOfHeader = true;
  77593. }
  77594. } while (!endOfHeader);
  77595. if (!findFormat) {
  77596. throw "HDR Bad header format, unsupported FORMAT";
  77597. }
  77598. lineIndex += (line.length + 1);
  77599. line = this.readStringLine(uint8array, lineIndex);
  77600. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  77601. var match = sizeRegexp.exec(line);
  77602. // TODO. Support +Y and -X if needed.
  77603. if (!match || match.length < 3) {
  77604. throw "HDR Bad header format, no size";
  77605. }
  77606. width = parseInt(match[2]);
  77607. height = parseInt(match[1]);
  77608. if (width < 8 || width > 0x7fff) {
  77609. throw "HDR Bad header format, unsupported size";
  77610. }
  77611. lineIndex += (line.length + 1);
  77612. return {
  77613. height: height,
  77614. width: width,
  77615. dataPosition: lineIndex
  77616. };
  77617. };
  77618. /**
  77619. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  77620. * This RGBE texture needs to store the information as a panorama.
  77621. *
  77622. * More information on this format are available here:
  77623. * https://en.wikipedia.org/wiki/RGBE_image_format
  77624. *
  77625. * @param buffer The binary file stored in an array buffer.
  77626. * @param size The expected size of the extracted cubemap.
  77627. * @return The Cube Map information.
  77628. */
  77629. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  77630. var uint8array = new Uint8Array(buffer);
  77631. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  77632. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  77633. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  77634. return cubeMapData;
  77635. };
  77636. /**
  77637. * Returns the pixels data extracted from an RGBE texture.
  77638. * This pixels will be stored left to right up to down in the R G B order in one array.
  77639. *
  77640. * More information on this format are available here:
  77641. * https://en.wikipedia.org/wiki/RGBE_image_format
  77642. *
  77643. * @param uint8array The binary file stored in an array buffer.
  77644. * @param hdrInfo The header information of the file.
  77645. * @return The pixels data in RGB right to left up to down order.
  77646. */
  77647. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  77648. // Keep for multi format supports.
  77649. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  77650. };
  77651. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  77652. var num_scanlines = hdrInfo.height;
  77653. var scanline_width = hdrInfo.width;
  77654. var a, b, c, d, count;
  77655. var dataIndex = hdrInfo.dataPosition;
  77656. var index = 0, endIndex = 0, i = 0;
  77657. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  77658. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  77659. // 3 channels of 4 bytes per pixel in float.
  77660. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  77661. var resultArray = new Float32Array(resultBuffer);
  77662. // read in each successive scanline
  77663. while (num_scanlines > 0) {
  77664. a = uint8array[dataIndex++];
  77665. b = uint8array[dataIndex++];
  77666. c = uint8array[dataIndex++];
  77667. d = uint8array[dataIndex++];
  77668. if (a != 2 || b != 2 || (c & 0x80)) {
  77669. // this file is not run length encoded
  77670. throw "HDR Bad header format, not RLE";
  77671. }
  77672. if (((c << 8) | d) != scanline_width) {
  77673. throw "HDR Bad header format, wrong scan line width";
  77674. }
  77675. index = 0;
  77676. // read each of the four channels for the scanline into the buffer
  77677. for (i = 0; i < 4; i++) {
  77678. endIndex = (i + 1) * scanline_width;
  77679. while (index < endIndex) {
  77680. a = uint8array[dataIndex++];
  77681. b = uint8array[dataIndex++];
  77682. if (a > 128) {
  77683. // a run of the same value
  77684. count = a - 128;
  77685. if ((count == 0) || (count > endIndex - index)) {
  77686. throw "HDR Bad Format, bad scanline data (run)";
  77687. }
  77688. while (count-- > 0) {
  77689. scanLineArray[index++] = b;
  77690. }
  77691. }
  77692. else {
  77693. // a non-run
  77694. count = a;
  77695. if ((count == 0) || (count > endIndex - index)) {
  77696. throw "HDR Bad Format, bad scanline data (non-run)";
  77697. }
  77698. scanLineArray[index++] = b;
  77699. if (--count > 0) {
  77700. for (var j = 0; j < count; j++) {
  77701. scanLineArray[index++] = uint8array[dataIndex++];
  77702. }
  77703. }
  77704. }
  77705. }
  77706. }
  77707. // now convert data from buffer into floats
  77708. for (i = 0; i < scanline_width; i++) {
  77709. a = scanLineArray[i];
  77710. b = scanLineArray[i + scanline_width];
  77711. c = scanLineArray[i + 2 * scanline_width];
  77712. d = scanLineArray[i + 3 * scanline_width];
  77713. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  77714. }
  77715. num_scanlines--;
  77716. }
  77717. return resultArray;
  77718. };
  77719. return HDRTools;
  77720. }());
  77721. BABYLON.HDRTools = HDRTools;
  77722. })(BABYLON || (BABYLON = {}));
  77723. //# sourceMappingURL=babylon.hdr.js.map
  77724. "use strict";
  77725. var BABYLON;
  77726. (function (BABYLON) {
  77727. /**
  77728. * This represents a texture coming from an HDR input.
  77729. *
  77730. * The only supported format is currently panorama picture stored in RGBE format.
  77731. * Example of such files can be found on HDRLib: http://hdrlib.com/
  77732. */
  77733. var HDRCubeTexture = /** @class */ (function (_super) {
  77734. __extends(HDRCubeTexture, _super);
  77735. /**
  77736. * Instantiates an HDRTexture from the following parameters.
  77737. *
  77738. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  77739. * @param scene The scene the texture will be used in
  77740. * @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.
  77741. * @param noMipmap Forces to not generate the mipmap if true
  77742. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  77743. * @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)
  77744. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  77745. */
  77746. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  77747. if (noMipmap === void 0) { noMipmap = false; }
  77748. if (generateHarmonics === void 0) { generateHarmonics = true; }
  77749. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  77750. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  77751. if (onLoad === void 0) { onLoad = null; }
  77752. if (onError === void 0) { onError = null; }
  77753. var _this = _super.call(this, scene) || this;
  77754. _this._useInGammaSpace = false;
  77755. _this._generateHarmonics = true;
  77756. _this._isBABYLONPreprocessed = false;
  77757. _this._onLoad = null;
  77758. _this._onError = null;
  77759. /**
  77760. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  77761. */
  77762. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  77763. /**
  77764. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  77765. * This is usefull at run time to apply the good shader.
  77766. */
  77767. _this.isPMREM = false;
  77768. _this._isBlocking = true;
  77769. /**
  77770. * Gets or sets the center of the bounding box associated with the cube texture
  77771. * It must define where the camera used to render the texture was set
  77772. */
  77773. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  77774. if (!url) {
  77775. return _this;
  77776. }
  77777. _this.name = url;
  77778. _this.url = url;
  77779. _this.hasAlpha = false;
  77780. _this.isCube = true;
  77781. _this._textureMatrix = BABYLON.Matrix.Identity();
  77782. _this._onLoad = onLoad;
  77783. _this._onError = onError;
  77784. _this.gammaSpace = false;
  77785. var caps = scene.getEngine().getCaps();
  77786. if (size) {
  77787. _this._isBABYLONPreprocessed = false;
  77788. _this._noMipmap = noMipmap;
  77789. _this._size = size;
  77790. _this._useInGammaSpace = useInGammaSpace;
  77791. _this._usePMREMGenerator = usePMREMGenerator &&
  77792. caps.textureLOD &&
  77793. caps.textureFloat &&
  77794. !_this._useInGammaSpace;
  77795. }
  77796. else {
  77797. _this._isBABYLONPreprocessed = true;
  77798. _this._noMipmap = false;
  77799. _this._useInGammaSpace = false;
  77800. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  77801. !_this._useInGammaSpace;
  77802. }
  77803. _this.isPMREM = _this._usePMREMGenerator;
  77804. _this._texture = _this._getFromCache(url, _this._noMipmap);
  77805. if (!_this._texture) {
  77806. if (!scene.useDelayedTextureLoading) {
  77807. _this.loadTexture();
  77808. }
  77809. else {
  77810. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  77811. }
  77812. }
  77813. return _this;
  77814. }
  77815. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  77816. /**
  77817. * Gets wether or not the texture is blocking during loading.
  77818. */
  77819. get: function () {
  77820. return this._isBlocking;
  77821. },
  77822. /**
  77823. * Sets wether or not the texture is blocking during loading.
  77824. */
  77825. set: function (value) {
  77826. this._isBlocking = value;
  77827. },
  77828. enumerable: true,
  77829. configurable: true
  77830. });
  77831. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  77832. get: function () {
  77833. return this._boundingBoxSize;
  77834. },
  77835. /**
  77836. * Gets or sets the size of the bounding box associated with the cube texture
  77837. * When defined, the cubemap will switch to local mode
  77838. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  77839. * @example https://www.babylonjs-playground.com/#RNASML
  77840. */
  77841. set: function (value) {
  77842. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  77843. return;
  77844. }
  77845. this._boundingBoxSize = value;
  77846. var scene = this.getScene();
  77847. if (scene) {
  77848. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  77849. }
  77850. },
  77851. enumerable: true,
  77852. configurable: true
  77853. });
  77854. /**
  77855. * Occurs when the file is a preprocessed .babylon.hdr file.
  77856. */
  77857. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  77858. var _this = this;
  77859. var mipLevels = 0;
  77860. var floatArrayView = null;
  77861. var scene = this.getScene();
  77862. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  77863. var mips = new Array();
  77864. if (!floatArrayView) {
  77865. return mips;
  77866. }
  77867. var startIndex = 30;
  77868. for (var level = 0; level < mipLevels; level++) {
  77869. mips.push([]);
  77870. // Fill each pixel of the mip level.
  77871. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  77872. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  77873. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  77874. mips[level].push(faceData);
  77875. startIndex += faceSize;
  77876. }
  77877. }
  77878. return mips;
  77879. } : null;
  77880. var callback = function (buffer) {
  77881. var scene = _this.getScene();
  77882. if (!scene) {
  77883. return null;
  77884. }
  77885. // Create Native Array Views
  77886. var intArrayView = new Int32Array(buffer);
  77887. floatArrayView = new Float32Array(buffer);
  77888. // Fill header.
  77889. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  77890. _this._size = intArrayView[1]; // CubeMap max mip face size.
  77891. // Update Texture Information.
  77892. if (!_this._texture) {
  77893. return null;
  77894. }
  77895. _this._texture.updateSize(_this._size, _this._size);
  77896. // Fill polynomial information.
  77897. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  77898. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  77899. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  77900. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  77901. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  77902. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  77903. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  77904. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  77905. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  77906. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  77907. _this.sphericalPolynomial = sphericalPolynomial;
  77908. // Fill pixel data.
  77909. mipLevels = intArrayView[29]; // Number of mip levels.
  77910. var startIndex = 30;
  77911. var data = [];
  77912. var faceSize = Math.pow(_this._size, 2) * 3;
  77913. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  77914. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  77915. startIndex += faceSize;
  77916. }
  77917. var results = [];
  77918. var byteArray = null;
  77919. // Push each faces.
  77920. for (var k = 0; k < 6; k++) {
  77921. var dataFace = null;
  77922. // To be deprecated.
  77923. if (version === 1) {
  77924. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  77925. dataFace = data[j];
  77926. }
  77927. // If special cases.
  77928. if (!mipmapGenerator && dataFace) {
  77929. if (!scene.getEngine().getCaps().textureFloat) {
  77930. // 3 channels of 1 bytes per pixel in bytes.
  77931. var byteBuffer = new ArrayBuffer(faceSize);
  77932. byteArray = new Uint8Array(byteBuffer);
  77933. }
  77934. for (var i = 0; i < _this._size * _this._size; i++) {
  77935. // Put in gamma space if requested.
  77936. if (_this._useInGammaSpace) {
  77937. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  77938. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  77939. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  77940. }
  77941. // Convert to int texture for fallback.
  77942. if (byteArray) {
  77943. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  77944. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  77945. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  77946. // May use luminance instead if the result is not accurate.
  77947. var max = Math.max(Math.max(r, g), b);
  77948. if (max > 255) {
  77949. var scale = 255 / max;
  77950. r *= scale;
  77951. g *= scale;
  77952. b *= scale;
  77953. }
  77954. byteArray[(i * 3) + 0] = r;
  77955. byteArray[(i * 3) + 1] = g;
  77956. byteArray[(i * 3) + 2] = b;
  77957. }
  77958. }
  77959. }
  77960. // Fill the array accordingly.
  77961. if (byteArray) {
  77962. results.push(byteArray);
  77963. }
  77964. else {
  77965. results.push(dataFace);
  77966. }
  77967. }
  77968. return results;
  77969. };
  77970. if (scene) {
  77971. 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);
  77972. }
  77973. };
  77974. /**
  77975. * Occurs when the file is raw .hdr file.
  77976. */
  77977. HDRCubeTexture.prototype.loadHDRTexture = function () {
  77978. var _this = this;
  77979. var callback = function (buffer) {
  77980. var scene = _this.getScene();
  77981. if (!scene) {
  77982. return null;
  77983. }
  77984. // Extract the raw linear data.
  77985. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  77986. // Generate harmonics if needed.
  77987. if (_this._generateHarmonics) {
  77988. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  77989. _this.sphericalPolynomial = sphericalPolynomial;
  77990. }
  77991. var results = [];
  77992. var byteArray = null;
  77993. // Push each faces.
  77994. for (var j = 0; j < 6; j++) {
  77995. // Create uintarray fallback.
  77996. if (!scene.getEngine().getCaps().textureFloat) {
  77997. // 3 channels of 1 bytes per pixel in bytes.
  77998. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  77999. byteArray = new Uint8Array(byteBuffer);
  78000. }
  78001. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  78002. // If special cases.
  78003. if (_this._useInGammaSpace || byteArray) {
  78004. for (var i = 0; i < _this._size * _this._size; i++) {
  78005. // Put in gamma space if requested.
  78006. if (_this._useInGammaSpace) {
  78007. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  78008. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  78009. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  78010. }
  78011. // Convert to int texture for fallback.
  78012. if (byteArray) {
  78013. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  78014. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  78015. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  78016. // May use luminance instead if the result is not accurate.
  78017. var max = Math.max(Math.max(r, g), b);
  78018. if (max > 255) {
  78019. var scale = 255 / max;
  78020. r *= scale;
  78021. g *= scale;
  78022. b *= scale;
  78023. }
  78024. byteArray[(i * 3) + 0] = r;
  78025. byteArray[(i * 3) + 1] = g;
  78026. byteArray[(i * 3) + 2] = b;
  78027. }
  78028. }
  78029. }
  78030. if (byteArray) {
  78031. results.push(byteArray);
  78032. }
  78033. else {
  78034. results.push(dataFace);
  78035. }
  78036. }
  78037. return results;
  78038. };
  78039. var mipmapGenerator = null;
  78040. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  78041. // if (!this._noMipmap &&
  78042. // this._usePMREMGenerator) {
  78043. // mipmapGenerator = (data: ArrayBufferView[]) => {
  78044. // // Custom setup of the generator matching with the PBR shader values.
  78045. // var generator = new BABYLON.PMREMGenerator(data,
  78046. // this._size,
  78047. // this._size,
  78048. // 0,
  78049. // 3,
  78050. // this.getScene().getEngine().getCaps().textureFloat,
  78051. // 2048,
  78052. // 0.25,
  78053. // false,
  78054. // true);
  78055. // return generator.filterCubeMap();
  78056. // };
  78057. // }
  78058. var scene = this.getScene();
  78059. if (scene) {
  78060. 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);
  78061. }
  78062. };
  78063. /**
  78064. * Starts the loading process of the texture.
  78065. */
  78066. HDRCubeTexture.prototype.loadTexture = function () {
  78067. if (this._isBABYLONPreprocessed) {
  78068. this.loadBabylonTexture();
  78069. }
  78070. else {
  78071. this.loadHDRTexture();
  78072. }
  78073. };
  78074. HDRCubeTexture.prototype.clone = function () {
  78075. var scene = this.getScene();
  78076. if (!scene) {
  78077. return this;
  78078. }
  78079. var size = (this._isBABYLONPreprocessed ? null : this._size);
  78080. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  78081. // Base texture
  78082. newTexture.level = this.level;
  78083. newTexture.wrapU = this.wrapU;
  78084. newTexture.wrapV = this.wrapV;
  78085. newTexture.coordinatesIndex = this.coordinatesIndex;
  78086. newTexture.coordinatesMode = this.coordinatesMode;
  78087. return newTexture;
  78088. };
  78089. // Methods
  78090. HDRCubeTexture.prototype.delayLoad = function () {
  78091. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  78092. return;
  78093. }
  78094. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  78095. this._texture = this._getFromCache(this.url, this._noMipmap);
  78096. if (!this._texture) {
  78097. this.loadTexture();
  78098. }
  78099. };
  78100. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  78101. return this._textureMatrix;
  78102. };
  78103. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  78104. this._textureMatrix = value;
  78105. };
  78106. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  78107. var texture = null;
  78108. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  78109. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  78110. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  78111. texture.name = parsedTexture.name;
  78112. texture.hasAlpha = parsedTexture.hasAlpha;
  78113. texture.level = parsedTexture.level;
  78114. texture.coordinatesMode = parsedTexture.coordinatesMode;
  78115. texture.isBlocking = parsedTexture.isBlocking;
  78116. }
  78117. if (texture) {
  78118. if (parsedTexture.boundingBoxPosition) {
  78119. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  78120. }
  78121. if (parsedTexture.boundingBoxSize) {
  78122. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  78123. }
  78124. }
  78125. return texture;
  78126. };
  78127. HDRCubeTexture.prototype.serialize = function () {
  78128. if (!this.name) {
  78129. return null;
  78130. }
  78131. var serializationObject = {};
  78132. serializationObject.name = this.name;
  78133. serializationObject.hasAlpha = this.hasAlpha;
  78134. serializationObject.isCube = true;
  78135. serializationObject.level = this.level;
  78136. serializationObject.size = this._size;
  78137. serializationObject.coordinatesMode = this.coordinatesMode;
  78138. serializationObject.useInGammaSpace = this._useInGammaSpace;
  78139. serializationObject.generateHarmonics = this._generateHarmonics;
  78140. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  78141. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  78142. serializationObject.customType = "BABYLON.HDRCubeTexture";
  78143. serializationObject.noMipmap = this._noMipmap;
  78144. serializationObject.isBlocking = this._isBlocking;
  78145. return serializationObject;
  78146. };
  78147. /**
  78148. * Saves as a file the data contained in the texture in a binary format.
  78149. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  78150. * as the spherical used in the lighting.
  78151. * @param url The HDR file url.
  78152. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  78153. * @param onError Method called if any error happens during download.
  78154. * @return The packed binary data.
  78155. */
  78156. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  78157. if (onError === void 0) { onError = null; }
  78158. var callback = function (buffer) {
  78159. var data = new Blob([buffer], { type: 'application/octet-stream' });
  78160. // Returns a URL you can use as a href.
  78161. var objUrl = window.URL.createObjectURL(data);
  78162. // Simulates a link to it and click to dowload.
  78163. var a = document.createElement("a");
  78164. document.body.appendChild(a);
  78165. a.style.display = "none";
  78166. a.href = objUrl;
  78167. a.download = "envmap.babylon.hdr";
  78168. a.click();
  78169. };
  78170. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  78171. };
  78172. /**
  78173. * Serializes the data contained in the texture in a binary format.
  78174. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  78175. * as the spherical used in the lighting.
  78176. * @param url The HDR file url.
  78177. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  78178. * @param onError Method called if any error happens during download.
  78179. * @return The packed binary data.
  78180. */
  78181. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  78182. if (onError === void 0) { onError = null; }
  78183. // Needs the url tho create the texture.
  78184. if (!url) {
  78185. return;
  78186. }
  78187. // Check Power of two size.
  78188. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  78189. return;
  78190. }
  78191. // Coming Back in 3.x.
  78192. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  78193. };
  78194. HDRCubeTexture._facesMapping = [
  78195. "right",
  78196. "left",
  78197. "up",
  78198. "down",
  78199. "front",
  78200. "back"
  78201. ];
  78202. return HDRCubeTexture;
  78203. }(BABYLON.BaseTexture));
  78204. BABYLON.HDRCubeTexture = HDRCubeTexture;
  78205. })(BABYLON || (BABYLON = {}));
  78206. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  78207. "use strict";
  78208. var BABYLON;
  78209. (function (BABYLON) {
  78210. var IndexedVector2 = /** @class */ (function (_super) {
  78211. __extends(IndexedVector2, _super);
  78212. function IndexedVector2(original, index) {
  78213. var _this = _super.call(this, original.x, original.y) || this;
  78214. _this.index = index;
  78215. return _this;
  78216. }
  78217. return IndexedVector2;
  78218. }(BABYLON.Vector2));
  78219. var PolygonPoints = /** @class */ (function () {
  78220. function PolygonPoints() {
  78221. this.elements = new Array();
  78222. }
  78223. PolygonPoints.prototype.add = function (originalPoints) {
  78224. var _this = this;
  78225. var result = new Array();
  78226. originalPoints.forEach(function (point) {
  78227. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  78228. var newPoint = new IndexedVector2(point, _this.elements.length);
  78229. result.push(newPoint);
  78230. _this.elements.push(newPoint);
  78231. }
  78232. });
  78233. return result;
  78234. };
  78235. PolygonPoints.prototype.computeBounds = function () {
  78236. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  78237. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  78238. this.elements.forEach(function (point) {
  78239. // x
  78240. if (point.x < lmin.x) {
  78241. lmin.x = point.x;
  78242. }
  78243. else if (point.x > lmax.x) {
  78244. lmax.x = point.x;
  78245. }
  78246. // y
  78247. if (point.y < lmin.y) {
  78248. lmin.y = point.y;
  78249. }
  78250. else if (point.y > lmax.y) {
  78251. lmax.y = point.y;
  78252. }
  78253. });
  78254. return {
  78255. min: lmin,
  78256. max: lmax,
  78257. width: lmax.x - lmin.x,
  78258. height: lmax.y - lmin.y
  78259. };
  78260. };
  78261. return PolygonPoints;
  78262. }());
  78263. var Polygon = /** @class */ (function () {
  78264. function Polygon() {
  78265. }
  78266. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  78267. return [
  78268. new BABYLON.Vector2(xmin, ymin),
  78269. new BABYLON.Vector2(xmax, ymin),
  78270. new BABYLON.Vector2(xmax, ymax),
  78271. new BABYLON.Vector2(xmin, ymax)
  78272. ];
  78273. };
  78274. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  78275. if (cx === void 0) { cx = 0; }
  78276. if (cy === void 0) { cy = 0; }
  78277. if (numberOfSides === void 0) { numberOfSides = 32; }
  78278. var result = new Array();
  78279. var angle = 0;
  78280. var increment = (Math.PI * 2) / numberOfSides;
  78281. for (var i = 0; i < numberOfSides; i++) {
  78282. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  78283. angle -= increment;
  78284. }
  78285. return result;
  78286. };
  78287. Polygon.Parse = function (input) {
  78288. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  78289. var i, result = [];
  78290. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  78291. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  78292. }
  78293. return result;
  78294. };
  78295. Polygon.StartingAt = function (x, y) {
  78296. return BABYLON.Path2.StartingAt(x, y);
  78297. };
  78298. return Polygon;
  78299. }());
  78300. BABYLON.Polygon = Polygon;
  78301. var PolygonMeshBuilder = /** @class */ (function () {
  78302. function PolygonMeshBuilder(name, contours, scene) {
  78303. this._points = new PolygonPoints();
  78304. this._outlinepoints = new PolygonPoints();
  78305. this._holes = new Array();
  78306. this._epoints = new Array();
  78307. this._eholes = new Array();
  78308. this._name = name;
  78309. this._scene = scene;
  78310. var points;
  78311. if (contours instanceof BABYLON.Path2) {
  78312. points = contours.getPoints();
  78313. }
  78314. else {
  78315. points = contours;
  78316. }
  78317. this._addToepoint(points);
  78318. this._points.add(points);
  78319. this._outlinepoints.add(points);
  78320. if (typeof earcut === 'undefined') {
  78321. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  78322. }
  78323. }
  78324. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  78325. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  78326. var p = points_1[_i];
  78327. this._epoints.push(p.x, p.y);
  78328. }
  78329. };
  78330. PolygonMeshBuilder.prototype.addHole = function (hole) {
  78331. this._points.add(hole);
  78332. var holepoints = new PolygonPoints();
  78333. holepoints.add(hole);
  78334. this._holes.push(holepoints);
  78335. this._eholes.push(this._epoints.length / 2);
  78336. this._addToepoint(hole);
  78337. return this;
  78338. };
  78339. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  78340. var _this = this;
  78341. if (updatable === void 0) { updatable = false; }
  78342. if (depth === void 0) { depth = 0; }
  78343. var result = new BABYLON.Mesh(this._name, this._scene);
  78344. var normals = new Array();
  78345. var positions = new Array();
  78346. var uvs = new Array();
  78347. var bounds = this._points.computeBounds();
  78348. this._points.elements.forEach(function (p) {
  78349. normals.push(0, 1.0, 0);
  78350. positions.push(p.x, 0, p.y);
  78351. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  78352. });
  78353. var indices = new Array();
  78354. var res = earcut(this._epoints, this._eholes, 2);
  78355. for (var i = 0; i < res.length; i++) {
  78356. indices.push(res[i]);
  78357. }
  78358. if (depth > 0) {
  78359. var positionscount = (positions.length / 3); //get the current pointcount
  78360. this._points.elements.forEach(function (p) {
  78361. normals.push(0, -1.0, 0);
  78362. positions.push(p.x, -depth, p.y);
  78363. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  78364. });
  78365. var totalCount = indices.length;
  78366. for (var i = 0; i < totalCount; i += 3) {
  78367. var i0 = indices[i + 0];
  78368. var i1 = indices[i + 1];
  78369. var i2 = indices[i + 2];
  78370. indices.push(i2 + positionscount);
  78371. indices.push(i1 + positionscount);
  78372. indices.push(i0 + positionscount);
  78373. }
  78374. //Add the sides
  78375. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  78376. this._holes.forEach(function (hole) {
  78377. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  78378. });
  78379. }
  78380. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  78381. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  78382. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  78383. result.setIndices(indices);
  78384. return result;
  78385. };
  78386. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  78387. var StartIndex = positions.length / 3;
  78388. var ulength = 0;
  78389. for (var i = 0; i < points.elements.length; i++) {
  78390. var p = points.elements[i];
  78391. var p1;
  78392. if ((i + 1) > points.elements.length - 1) {
  78393. p1 = points.elements[0];
  78394. }
  78395. else {
  78396. p1 = points.elements[i + 1];
  78397. }
  78398. positions.push(p.x, 0, p.y);
  78399. positions.push(p.x, -depth, p.y);
  78400. positions.push(p1.x, 0, p1.y);
  78401. positions.push(p1.x, -depth, p1.y);
  78402. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  78403. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  78404. var v3 = v2.subtract(v1);
  78405. var v4 = new BABYLON.Vector3(0, 1, 0);
  78406. var vn = BABYLON.Vector3.Cross(v3, v4);
  78407. vn = vn.normalize();
  78408. uvs.push(ulength / bounds.width, 0);
  78409. uvs.push(ulength / bounds.width, 1);
  78410. ulength += v3.length();
  78411. uvs.push((ulength / bounds.width), 0);
  78412. uvs.push((ulength / bounds.width), 1);
  78413. if (!flip) {
  78414. normals.push(-vn.x, -vn.y, -vn.z);
  78415. normals.push(-vn.x, -vn.y, -vn.z);
  78416. normals.push(-vn.x, -vn.y, -vn.z);
  78417. normals.push(-vn.x, -vn.y, -vn.z);
  78418. indices.push(StartIndex);
  78419. indices.push(StartIndex + 1);
  78420. indices.push(StartIndex + 2);
  78421. indices.push(StartIndex + 1);
  78422. indices.push(StartIndex + 3);
  78423. indices.push(StartIndex + 2);
  78424. }
  78425. else {
  78426. normals.push(vn.x, vn.y, vn.z);
  78427. normals.push(vn.x, vn.y, vn.z);
  78428. normals.push(vn.x, vn.y, vn.z);
  78429. normals.push(vn.x, vn.y, vn.z);
  78430. indices.push(StartIndex);
  78431. indices.push(StartIndex + 2);
  78432. indices.push(StartIndex + 1);
  78433. indices.push(StartIndex + 1);
  78434. indices.push(StartIndex + 2);
  78435. indices.push(StartIndex + 3);
  78436. }
  78437. StartIndex += 4;
  78438. }
  78439. ;
  78440. };
  78441. return PolygonMeshBuilder;
  78442. }());
  78443. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  78444. })(BABYLON || (BABYLON = {}));
  78445. //# sourceMappingURL=babylon.polygonMesh.js.map
  78446. "use strict";
  78447. var BABYLON;
  78448. (function (BABYLON) {
  78449. // Unique ID when we import meshes from Babylon to CSG
  78450. var currentCSGMeshId = 0;
  78451. // # class Vertex
  78452. // Represents a vertex of a polygon. Use your own vertex class instead of this
  78453. // one to provide additional features like texture coordinates and vertex
  78454. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  78455. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  78456. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  78457. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  78458. // is not used anywhere else.
  78459. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  78460. var Vertex = /** @class */ (function () {
  78461. function Vertex(pos, normal, uv) {
  78462. this.pos = pos;
  78463. this.normal = normal;
  78464. this.uv = uv;
  78465. }
  78466. Vertex.prototype.clone = function () {
  78467. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  78468. };
  78469. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  78470. // orientation of a polygon is flipped.
  78471. Vertex.prototype.flip = function () {
  78472. this.normal = this.normal.scale(-1);
  78473. };
  78474. // Create a new vertex between this vertex and `other` by linearly
  78475. // interpolating all properties using a parameter of `t`. Subclasses should
  78476. // override this to interpolate additional properties.
  78477. Vertex.prototype.interpolate = function (other, t) {
  78478. 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));
  78479. };
  78480. return Vertex;
  78481. }());
  78482. // # class Plane
  78483. // Represents a plane in 3D space.
  78484. var Plane = /** @class */ (function () {
  78485. function Plane(normal, w) {
  78486. this.normal = normal;
  78487. this.w = w;
  78488. }
  78489. Plane.FromPoints = function (a, b, c) {
  78490. var v0 = c.subtract(a);
  78491. var v1 = b.subtract(a);
  78492. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  78493. return null;
  78494. }
  78495. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  78496. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  78497. };
  78498. Plane.prototype.clone = function () {
  78499. return new Plane(this.normal.clone(), this.w);
  78500. };
  78501. Plane.prototype.flip = function () {
  78502. this.normal.scaleInPlace(-1);
  78503. this.w = -this.w;
  78504. };
  78505. // Split `polygon` by this plane if needed, then put the polygon or polygon
  78506. // fragments in the appropriate lists. Coplanar polygons go into either
  78507. // `coplanarFront` or `coplanarBack` depending on their orientation with
  78508. // respect to this plane. Polygons in front or in back of this plane go into
  78509. // either `front` or `back`.
  78510. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  78511. var COPLANAR = 0;
  78512. var FRONT = 1;
  78513. var BACK = 2;
  78514. var SPANNING = 3;
  78515. // Classify each point as well as the entire polygon into one of the above
  78516. // four classes.
  78517. var polygonType = 0;
  78518. var types = [];
  78519. var i;
  78520. var t;
  78521. for (i = 0; i < polygon.vertices.length; i++) {
  78522. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  78523. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  78524. polygonType |= type;
  78525. types.push(type);
  78526. }
  78527. // Put the polygon in the correct list, splitting it when necessary.
  78528. switch (polygonType) {
  78529. case COPLANAR:
  78530. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  78531. break;
  78532. case FRONT:
  78533. front.push(polygon);
  78534. break;
  78535. case BACK:
  78536. back.push(polygon);
  78537. break;
  78538. case SPANNING:
  78539. var f = [], b = [];
  78540. for (i = 0; i < polygon.vertices.length; i++) {
  78541. var j = (i + 1) % polygon.vertices.length;
  78542. var ti = types[i], tj = types[j];
  78543. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  78544. if (ti !== BACK)
  78545. f.push(vi);
  78546. if (ti !== FRONT)
  78547. b.push(ti !== BACK ? vi.clone() : vi);
  78548. if ((ti | tj) === SPANNING) {
  78549. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  78550. var v = vi.interpolate(vj, t);
  78551. f.push(v);
  78552. b.push(v.clone());
  78553. }
  78554. }
  78555. var poly;
  78556. if (f.length >= 3) {
  78557. poly = new Polygon(f, polygon.shared);
  78558. if (poly.plane)
  78559. front.push(poly);
  78560. }
  78561. if (b.length >= 3) {
  78562. poly = new Polygon(b, polygon.shared);
  78563. if (poly.plane)
  78564. back.push(poly);
  78565. }
  78566. break;
  78567. }
  78568. };
  78569. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  78570. // point is on the plane.
  78571. Plane.EPSILON = 1e-5;
  78572. return Plane;
  78573. }());
  78574. // # class Polygon
  78575. // Represents a convex polygon. The vertices used to initialize a polygon must
  78576. // be coplanar and form a convex loop.
  78577. //
  78578. // Each convex polygon has a `shared` property, which is shared between all
  78579. // polygons that are clones of each other or were split from the same polygon.
  78580. // This can be used to define per-polygon properties (such as surface color).
  78581. var Polygon = /** @class */ (function () {
  78582. function Polygon(vertices, shared) {
  78583. this.vertices = vertices;
  78584. this.shared = shared;
  78585. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  78586. }
  78587. Polygon.prototype.clone = function () {
  78588. var vertices = this.vertices.map(function (v) { return v.clone(); });
  78589. return new Polygon(vertices, this.shared);
  78590. };
  78591. Polygon.prototype.flip = function () {
  78592. this.vertices.reverse().map(function (v) { v.flip(); });
  78593. this.plane.flip();
  78594. };
  78595. return Polygon;
  78596. }());
  78597. // # class Node
  78598. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  78599. // by picking a polygon to split along. That polygon (and all other coplanar
  78600. // polygons) are added directly to that node and the other polygons are added to
  78601. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  78602. // no distinction between internal and leaf nodes.
  78603. var Node = /** @class */ (function () {
  78604. function Node(polygons) {
  78605. this.plane = null;
  78606. this.front = null;
  78607. this.back = null;
  78608. this.polygons = new Array();
  78609. if (polygons) {
  78610. this.build(polygons);
  78611. }
  78612. }
  78613. Node.prototype.clone = function () {
  78614. var node = new Node();
  78615. node.plane = this.plane && this.plane.clone();
  78616. node.front = this.front && this.front.clone();
  78617. node.back = this.back && this.back.clone();
  78618. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  78619. return node;
  78620. };
  78621. // Convert solid space to empty space and empty space to solid space.
  78622. Node.prototype.invert = function () {
  78623. for (var i = 0; i < this.polygons.length; i++) {
  78624. this.polygons[i].flip();
  78625. }
  78626. if (this.plane) {
  78627. this.plane.flip();
  78628. }
  78629. if (this.front) {
  78630. this.front.invert();
  78631. }
  78632. if (this.back) {
  78633. this.back.invert();
  78634. }
  78635. var temp = this.front;
  78636. this.front = this.back;
  78637. this.back = temp;
  78638. };
  78639. // Recursively remove all polygons in `polygons` that are inside this BSP
  78640. // tree.
  78641. Node.prototype.clipPolygons = function (polygons) {
  78642. if (!this.plane)
  78643. return polygons.slice();
  78644. var front = new Array(), back = new Array();
  78645. for (var i = 0; i < polygons.length; i++) {
  78646. this.plane.splitPolygon(polygons[i], front, back, front, back);
  78647. }
  78648. if (this.front) {
  78649. front = this.front.clipPolygons(front);
  78650. }
  78651. if (this.back) {
  78652. back = this.back.clipPolygons(back);
  78653. }
  78654. else {
  78655. back = [];
  78656. }
  78657. return front.concat(back);
  78658. };
  78659. // Remove all polygons in this BSP tree that are inside the other BSP tree
  78660. // `bsp`.
  78661. Node.prototype.clipTo = function (bsp) {
  78662. this.polygons = bsp.clipPolygons(this.polygons);
  78663. if (this.front)
  78664. this.front.clipTo(bsp);
  78665. if (this.back)
  78666. this.back.clipTo(bsp);
  78667. };
  78668. // Return a list of all polygons in this BSP tree.
  78669. Node.prototype.allPolygons = function () {
  78670. var polygons = this.polygons.slice();
  78671. if (this.front)
  78672. polygons = polygons.concat(this.front.allPolygons());
  78673. if (this.back)
  78674. polygons = polygons.concat(this.back.allPolygons());
  78675. return polygons;
  78676. };
  78677. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  78678. // new polygons are filtered down to the bottom of the tree and become new
  78679. // nodes there. Each set of polygons is partitioned using the first polygon
  78680. // (no heuristic is used to pick a good split).
  78681. Node.prototype.build = function (polygons) {
  78682. if (!polygons.length)
  78683. return;
  78684. if (!this.plane)
  78685. this.plane = polygons[0].plane.clone();
  78686. var front = new Array(), back = new Array();
  78687. for (var i = 0; i < polygons.length; i++) {
  78688. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  78689. }
  78690. if (front.length) {
  78691. if (!this.front)
  78692. this.front = new Node();
  78693. this.front.build(front);
  78694. }
  78695. if (back.length) {
  78696. if (!this.back)
  78697. this.back = new Node();
  78698. this.back.build(back);
  78699. }
  78700. };
  78701. return Node;
  78702. }());
  78703. var CSG = /** @class */ (function () {
  78704. function CSG() {
  78705. this.polygons = new Array();
  78706. }
  78707. // Convert BABYLON.Mesh to BABYLON.CSG
  78708. CSG.FromMesh = function (mesh) {
  78709. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  78710. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  78711. if (mesh instanceof BABYLON.Mesh) {
  78712. mesh.computeWorldMatrix(true);
  78713. matrix = mesh.getWorldMatrix();
  78714. meshPosition = mesh.position.clone();
  78715. meshRotation = mesh.rotation.clone();
  78716. if (mesh.rotationQuaternion) {
  78717. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  78718. }
  78719. meshScaling = mesh.scaling.clone();
  78720. }
  78721. else {
  78722. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  78723. }
  78724. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  78725. var subMeshes = mesh.subMeshes;
  78726. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  78727. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  78728. vertices = [];
  78729. for (var j = 0; j < 3; j++) {
  78730. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  78731. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  78732. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  78733. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  78734. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  78735. vertex = new Vertex(position, normal, uv);
  78736. vertices.push(vertex);
  78737. }
  78738. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  78739. // To handle the case of degenerated triangle
  78740. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  78741. if (polygon.plane)
  78742. polygons.push(polygon);
  78743. }
  78744. }
  78745. var csg = CSG.FromPolygons(polygons);
  78746. csg.matrix = matrix;
  78747. csg.position = meshPosition;
  78748. csg.rotation = meshRotation;
  78749. csg.scaling = meshScaling;
  78750. csg.rotationQuaternion = meshRotationQuaternion;
  78751. currentCSGMeshId++;
  78752. return csg;
  78753. };
  78754. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  78755. CSG.FromPolygons = function (polygons) {
  78756. var csg = new CSG();
  78757. csg.polygons = polygons;
  78758. return csg;
  78759. };
  78760. CSG.prototype.clone = function () {
  78761. var csg = new CSG();
  78762. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  78763. csg.copyTransformAttributes(this);
  78764. return csg;
  78765. };
  78766. CSG.prototype.union = function (csg) {
  78767. var a = new Node(this.clone().polygons);
  78768. var b = new Node(csg.clone().polygons);
  78769. a.clipTo(b);
  78770. b.clipTo(a);
  78771. b.invert();
  78772. b.clipTo(a);
  78773. b.invert();
  78774. a.build(b.allPolygons());
  78775. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  78776. };
  78777. CSG.prototype.unionInPlace = function (csg) {
  78778. var a = new Node(this.polygons);
  78779. var b = new Node(csg.polygons);
  78780. a.clipTo(b);
  78781. b.clipTo(a);
  78782. b.invert();
  78783. b.clipTo(a);
  78784. b.invert();
  78785. a.build(b.allPolygons());
  78786. this.polygons = a.allPolygons();
  78787. };
  78788. CSG.prototype.subtract = function (csg) {
  78789. var a = new Node(this.clone().polygons);
  78790. var b = new Node(csg.clone().polygons);
  78791. a.invert();
  78792. a.clipTo(b);
  78793. b.clipTo(a);
  78794. b.invert();
  78795. b.clipTo(a);
  78796. b.invert();
  78797. a.build(b.allPolygons());
  78798. a.invert();
  78799. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  78800. };
  78801. CSG.prototype.subtractInPlace = function (csg) {
  78802. var a = new Node(this.polygons);
  78803. var b = new Node(csg.polygons);
  78804. a.invert();
  78805. a.clipTo(b);
  78806. b.clipTo(a);
  78807. b.invert();
  78808. b.clipTo(a);
  78809. b.invert();
  78810. a.build(b.allPolygons());
  78811. a.invert();
  78812. this.polygons = a.allPolygons();
  78813. };
  78814. CSG.prototype.intersect = function (csg) {
  78815. var a = new Node(this.clone().polygons);
  78816. var b = new Node(csg.clone().polygons);
  78817. a.invert();
  78818. b.clipTo(a);
  78819. b.invert();
  78820. a.clipTo(b);
  78821. b.clipTo(a);
  78822. a.build(b.allPolygons());
  78823. a.invert();
  78824. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  78825. };
  78826. CSG.prototype.intersectInPlace = function (csg) {
  78827. var a = new Node(this.polygons);
  78828. var b = new Node(csg.polygons);
  78829. a.invert();
  78830. b.clipTo(a);
  78831. b.invert();
  78832. a.clipTo(b);
  78833. b.clipTo(a);
  78834. a.build(b.allPolygons());
  78835. a.invert();
  78836. this.polygons = a.allPolygons();
  78837. };
  78838. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  78839. // not modified.
  78840. CSG.prototype.inverse = function () {
  78841. var csg = this.clone();
  78842. csg.inverseInPlace();
  78843. return csg;
  78844. };
  78845. CSG.prototype.inverseInPlace = function () {
  78846. this.polygons.map(function (p) { p.flip(); });
  78847. };
  78848. // This is used to keep meshes transformations so they can be restored
  78849. // when we build back a Babylon Mesh
  78850. // NB : All CSG operations are performed in world coordinates
  78851. CSG.prototype.copyTransformAttributes = function (csg) {
  78852. this.matrix = csg.matrix;
  78853. this.position = csg.position;
  78854. this.rotation = csg.rotation;
  78855. this.scaling = csg.scaling;
  78856. this.rotationQuaternion = csg.rotationQuaternion;
  78857. return this;
  78858. };
  78859. // Build Raw mesh from CSG
  78860. // Coordinates here are in world space
  78861. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  78862. var matrix = this.matrix.clone();
  78863. matrix.invert();
  78864. 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;
  78865. if (keepSubMeshes) {
  78866. // Sort Polygons, since subMeshes are indices range
  78867. polygons.sort(function (a, b) {
  78868. if (a.shared.meshId === b.shared.meshId) {
  78869. return a.shared.subMeshId - b.shared.subMeshId;
  78870. }
  78871. else {
  78872. return a.shared.meshId - b.shared.meshId;
  78873. }
  78874. });
  78875. }
  78876. for (var i = 0, il = polygons.length; i < il; i++) {
  78877. polygon = polygons[i];
  78878. // Building SubMeshes
  78879. if (!subMesh_dict[polygon.shared.meshId]) {
  78880. subMesh_dict[polygon.shared.meshId] = {};
  78881. }
  78882. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  78883. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  78884. indexStart: +Infinity,
  78885. indexEnd: -Infinity,
  78886. materialIndex: polygon.shared.materialIndex
  78887. };
  78888. }
  78889. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  78890. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  78891. polygonIndices[0] = 0;
  78892. polygonIndices[1] = j - 1;
  78893. polygonIndices[2] = j;
  78894. for (var k = 0; k < 3; k++) {
  78895. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  78896. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  78897. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  78898. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  78899. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  78900. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  78901. // Check if 2 points can be merged
  78902. if (!(typeof vertex_idx !== 'undefined' &&
  78903. normals[vertex_idx * 3] === localNormal.x &&
  78904. normals[vertex_idx * 3 + 1] === localNormal.y &&
  78905. normals[vertex_idx * 3 + 2] === localNormal.z &&
  78906. uvs[vertex_idx * 2] === uv.x &&
  78907. uvs[vertex_idx * 2 + 1] === uv.y)) {
  78908. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  78909. uvs.push(uv.x, uv.y);
  78910. normals.push(normal.x, normal.y, normal.z);
  78911. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  78912. }
  78913. indices.push(vertex_idx);
  78914. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  78915. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  78916. currentIndex++;
  78917. }
  78918. }
  78919. }
  78920. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  78921. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  78922. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  78923. mesh.setIndices(indices, null);
  78924. if (keepSubMeshes) {
  78925. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  78926. var materialIndexOffset = 0, materialMaxIndex;
  78927. mesh.subMeshes = new Array();
  78928. for (var m in subMesh_dict) {
  78929. materialMaxIndex = -1;
  78930. for (var sm in subMesh_dict[m]) {
  78931. subMesh_obj = subMesh_dict[m][sm];
  78932. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  78933. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  78934. }
  78935. materialIndexOffset += ++materialMaxIndex;
  78936. }
  78937. }
  78938. return mesh;
  78939. };
  78940. // Build Mesh from CSG taking material and transforms into account
  78941. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  78942. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  78943. mesh.material = material;
  78944. mesh.position.copyFrom(this.position);
  78945. mesh.rotation.copyFrom(this.rotation);
  78946. if (this.rotationQuaternion) {
  78947. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  78948. }
  78949. mesh.scaling.copyFrom(this.scaling);
  78950. mesh.computeWorldMatrix(true);
  78951. return mesh;
  78952. };
  78953. return CSG;
  78954. }());
  78955. BABYLON.CSG = CSG;
  78956. })(BABYLON || (BABYLON = {}));
  78957. //# sourceMappingURL=babylon.csg.js.map
  78958. "use strict";
  78959. var BABYLON;
  78960. (function (BABYLON) {
  78961. var LensFlare = /** @class */ (function () {
  78962. function LensFlare(size, position, color, imgUrl, system) {
  78963. this.size = size;
  78964. this.position = position;
  78965. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  78966. this.color = color || new BABYLON.Color3(1, 1, 1);
  78967. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  78968. this._system = system;
  78969. system.lensFlares.push(this);
  78970. }
  78971. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  78972. return new LensFlare(size, position, color, imgUrl, system);
  78973. };
  78974. LensFlare.prototype.dispose = function () {
  78975. if (this.texture) {
  78976. this.texture.dispose();
  78977. }
  78978. // Remove from scene
  78979. var index = this._system.lensFlares.indexOf(this);
  78980. this._system.lensFlares.splice(index, 1);
  78981. };
  78982. ;
  78983. return LensFlare;
  78984. }());
  78985. BABYLON.LensFlare = LensFlare;
  78986. })(BABYLON || (BABYLON = {}));
  78987. //# sourceMappingURL=babylon.lensFlare.js.map
  78988. "use strict";
  78989. var BABYLON;
  78990. (function (BABYLON) {
  78991. var LensFlareSystem = /** @class */ (function () {
  78992. function LensFlareSystem(name, emitter, scene) {
  78993. this.name = name;
  78994. this.lensFlares = new Array();
  78995. this.borderLimit = 300;
  78996. this.viewportBorder = 0;
  78997. this.layerMask = 0x0FFFFFFF;
  78998. this._vertexBuffers = {};
  78999. this._isEnabled = true;
  79000. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79001. this._emitter = emitter;
  79002. this.id = name;
  79003. scene.lensFlareSystems.push(this);
  79004. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  79005. var engine = scene.getEngine();
  79006. // VBO
  79007. var vertices = [];
  79008. vertices.push(1, 1);
  79009. vertices.push(-1, 1);
  79010. vertices.push(-1, -1);
  79011. vertices.push(1, -1);
  79012. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  79013. // Indices
  79014. var indices = [];
  79015. indices.push(0);
  79016. indices.push(1);
  79017. indices.push(2);
  79018. indices.push(0);
  79019. indices.push(2);
  79020. indices.push(3);
  79021. this._indexBuffer = engine.createIndexBuffer(indices);
  79022. // Effects
  79023. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  79024. }
  79025. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  79026. get: function () {
  79027. return this._isEnabled;
  79028. },
  79029. set: function (value) {
  79030. this._isEnabled = value;
  79031. },
  79032. enumerable: true,
  79033. configurable: true
  79034. });
  79035. LensFlareSystem.prototype.getScene = function () {
  79036. return this._scene;
  79037. };
  79038. LensFlareSystem.prototype.getEmitter = function () {
  79039. return this._emitter;
  79040. };
  79041. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  79042. this._emitter = newEmitter;
  79043. };
  79044. LensFlareSystem.prototype.getEmitterPosition = function () {
  79045. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  79046. };
  79047. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  79048. var position = this.getEmitterPosition();
  79049. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  79050. this._positionX = position.x;
  79051. this._positionY = position.y;
  79052. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  79053. if (this.viewportBorder > 0) {
  79054. globalViewport.x -= this.viewportBorder;
  79055. globalViewport.y -= this.viewportBorder;
  79056. globalViewport.width += this.viewportBorder * 2;
  79057. globalViewport.height += this.viewportBorder * 2;
  79058. position.x += this.viewportBorder;
  79059. position.y += this.viewportBorder;
  79060. this._positionX += this.viewportBorder;
  79061. this._positionY += this.viewportBorder;
  79062. }
  79063. if (position.z > 0) {
  79064. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  79065. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  79066. return true;
  79067. }
  79068. return true;
  79069. }
  79070. return false;
  79071. };
  79072. LensFlareSystem.prototype._isVisible = function () {
  79073. if (!this._isEnabled || !this._scene.activeCamera) {
  79074. return false;
  79075. }
  79076. var emitterPosition = this.getEmitterPosition();
  79077. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  79078. var distance = direction.length();
  79079. direction.normalize();
  79080. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  79081. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  79082. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  79083. };
  79084. LensFlareSystem.prototype.render = function () {
  79085. if (!this._effect.isReady() || !this._scene.activeCamera)
  79086. return false;
  79087. var engine = this._scene.getEngine();
  79088. var viewport = this._scene.activeCamera.viewport;
  79089. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  79090. // Position
  79091. if (!this.computeEffectivePosition(globalViewport)) {
  79092. return false;
  79093. }
  79094. // Visibility
  79095. if (!this._isVisible()) {
  79096. return false;
  79097. }
  79098. // Intensity
  79099. var awayX;
  79100. var awayY;
  79101. if (this._positionX < this.borderLimit + globalViewport.x) {
  79102. awayX = this.borderLimit + globalViewport.x - this._positionX;
  79103. }
  79104. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  79105. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  79106. }
  79107. else {
  79108. awayX = 0;
  79109. }
  79110. if (this._positionY < this.borderLimit + globalViewport.y) {
  79111. awayY = this.borderLimit + globalViewport.y - this._positionY;
  79112. }
  79113. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  79114. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  79115. }
  79116. else {
  79117. awayY = 0;
  79118. }
  79119. var away = (awayX > awayY) ? awayX : awayY;
  79120. away -= this.viewportBorder;
  79121. if (away > this.borderLimit) {
  79122. away = this.borderLimit;
  79123. }
  79124. var intensity = 1.0 - (away / this.borderLimit);
  79125. if (intensity < 0) {
  79126. return false;
  79127. }
  79128. if (intensity > 1.0) {
  79129. intensity = 1.0;
  79130. }
  79131. if (this.viewportBorder > 0) {
  79132. globalViewport.x += this.viewportBorder;
  79133. globalViewport.y += this.viewportBorder;
  79134. globalViewport.width -= this.viewportBorder * 2;
  79135. globalViewport.height -= this.viewportBorder * 2;
  79136. this._positionX -= this.viewportBorder;
  79137. this._positionY -= this.viewportBorder;
  79138. }
  79139. // Position
  79140. var centerX = globalViewport.x + globalViewport.width / 2;
  79141. var centerY = globalViewport.y + globalViewport.height / 2;
  79142. var distX = centerX - this._positionX;
  79143. var distY = centerY - this._positionY;
  79144. // Effects
  79145. engine.enableEffect(this._effect);
  79146. engine.setState(false);
  79147. engine.setDepthBuffer(false);
  79148. // VBOs
  79149. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  79150. // Flares
  79151. for (var index = 0; index < this.lensFlares.length; index++) {
  79152. var flare = this.lensFlares[index];
  79153. engine.setAlphaMode(flare.alphaMode);
  79154. var x = centerX - (distX * flare.position);
  79155. var y = centerY - (distY * flare.position);
  79156. var cw = flare.size;
  79157. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  79158. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  79159. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  79160. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  79161. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  79162. // Texture
  79163. this._effect.setTexture("textureSampler", flare.texture);
  79164. // Color
  79165. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  79166. // Draw order
  79167. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  79168. }
  79169. engine.setDepthBuffer(true);
  79170. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  79171. return true;
  79172. };
  79173. LensFlareSystem.prototype.dispose = function () {
  79174. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  79175. if (vertexBuffer) {
  79176. vertexBuffer.dispose();
  79177. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  79178. }
  79179. if (this._indexBuffer) {
  79180. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  79181. this._indexBuffer = null;
  79182. }
  79183. while (this.lensFlares.length) {
  79184. this.lensFlares[0].dispose();
  79185. }
  79186. // Remove from scene
  79187. var index = this._scene.lensFlareSystems.indexOf(this);
  79188. this._scene.lensFlareSystems.splice(index, 1);
  79189. };
  79190. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  79191. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  79192. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  79193. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  79194. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  79195. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  79196. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  79197. var parsedFlare = parsedLensFlareSystem.flares[index];
  79198. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  79199. }
  79200. return lensFlareSystem;
  79201. };
  79202. LensFlareSystem.prototype.serialize = function () {
  79203. var serializationObject = {};
  79204. serializationObject.id = this.id;
  79205. serializationObject.name = this.name;
  79206. serializationObject.emitterId = this.getEmitter().id;
  79207. serializationObject.borderLimit = this.borderLimit;
  79208. serializationObject.flares = [];
  79209. for (var index = 0; index < this.lensFlares.length; index++) {
  79210. var flare = this.lensFlares[index];
  79211. serializationObject.flares.push({
  79212. size: flare.size,
  79213. position: flare.position,
  79214. color: flare.color.asArray(),
  79215. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  79216. });
  79217. }
  79218. return serializationObject;
  79219. };
  79220. return LensFlareSystem;
  79221. }());
  79222. BABYLON.LensFlareSystem = LensFlareSystem;
  79223. })(BABYLON || (BABYLON = {}));
  79224. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  79225. "use strict";
  79226. var BABYLON;
  79227. (function (BABYLON) {
  79228. /**
  79229. * This is a holder class for the physics joint created by the physics plugin.
  79230. * It holds a set of functions to control the underlying joint.
  79231. */
  79232. var PhysicsJoint = /** @class */ (function () {
  79233. function PhysicsJoint(type, jointData) {
  79234. this.type = type;
  79235. this.jointData = jointData;
  79236. jointData.nativeParams = jointData.nativeParams || {};
  79237. }
  79238. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  79239. get: function () {
  79240. return this._physicsJoint;
  79241. },
  79242. set: function (newJoint) {
  79243. if (this._physicsJoint) {
  79244. //remove from the wolrd
  79245. }
  79246. this._physicsJoint = newJoint;
  79247. },
  79248. enumerable: true,
  79249. configurable: true
  79250. });
  79251. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  79252. set: function (physicsPlugin) {
  79253. this._physicsPlugin = physicsPlugin;
  79254. },
  79255. enumerable: true,
  79256. configurable: true
  79257. });
  79258. /**
  79259. * Execute a function that is physics-plugin specific.
  79260. * @param {Function} func the function that will be executed.
  79261. * It accepts two parameters: the physics world and the physics joint.
  79262. */
  79263. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  79264. func(this._physicsPlugin.world, this._physicsJoint);
  79265. };
  79266. //TODO check if the native joints are the same
  79267. //Joint Types
  79268. PhysicsJoint.DistanceJoint = 0;
  79269. PhysicsJoint.HingeJoint = 1;
  79270. PhysicsJoint.BallAndSocketJoint = 2;
  79271. PhysicsJoint.WheelJoint = 3;
  79272. PhysicsJoint.SliderJoint = 4;
  79273. //OIMO
  79274. PhysicsJoint.PrismaticJoint = 5;
  79275. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  79276. PhysicsJoint.UniversalJoint = 6;
  79277. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  79278. //Cannon
  79279. //Similar to a Ball-Joint. Different in params
  79280. PhysicsJoint.PointToPointJoint = 8;
  79281. //Cannon only at the moment
  79282. PhysicsJoint.SpringJoint = 9;
  79283. PhysicsJoint.LockJoint = 10;
  79284. return PhysicsJoint;
  79285. }());
  79286. BABYLON.PhysicsJoint = PhysicsJoint;
  79287. /**
  79288. * A class representing a physics distance joint.
  79289. */
  79290. var DistanceJoint = /** @class */ (function (_super) {
  79291. __extends(DistanceJoint, _super);
  79292. function DistanceJoint(jointData) {
  79293. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  79294. }
  79295. /**
  79296. * Update the predefined distance.
  79297. */
  79298. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  79299. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  79300. };
  79301. return DistanceJoint;
  79302. }(PhysicsJoint));
  79303. BABYLON.DistanceJoint = DistanceJoint;
  79304. var MotorEnabledJoint = /** @class */ (function (_super) {
  79305. __extends(MotorEnabledJoint, _super);
  79306. function MotorEnabledJoint(type, jointData) {
  79307. return _super.call(this, type, jointData) || this;
  79308. }
  79309. /**
  79310. * Set the motor values.
  79311. * Attention, this function is plugin specific. Engines won't react 100% the same.
  79312. * @param {number} force the force to apply
  79313. * @param {number} maxForce max force for this motor.
  79314. */
  79315. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  79316. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  79317. };
  79318. /**
  79319. * Set the motor's limits.
  79320. * Attention, this function is plugin specific. Engines won't react 100% the same.
  79321. */
  79322. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  79323. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  79324. };
  79325. return MotorEnabledJoint;
  79326. }(PhysicsJoint));
  79327. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  79328. /**
  79329. * This class represents a single hinge physics joint
  79330. */
  79331. var HingeJoint = /** @class */ (function (_super) {
  79332. __extends(HingeJoint, _super);
  79333. function HingeJoint(jointData) {
  79334. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  79335. }
  79336. /**
  79337. * Set the motor values.
  79338. * Attention, this function is plugin specific. Engines won't react 100% the same.
  79339. * @param {number} force the force to apply
  79340. * @param {number} maxForce max force for this motor.
  79341. */
  79342. HingeJoint.prototype.setMotor = function (force, maxForce) {
  79343. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  79344. };
  79345. /**
  79346. * Set the motor's limits.
  79347. * Attention, this function is plugin specific. Engines won't react 100% the same.
  79348. */
  79349. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  79350. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  79351. };
  79352. return HingeJoint;
  79353. }(MotorEnabledJoint));
  79354. BABYLON.HingeJoint = HingeJoint;
  79355. /**
  79356. * This class represents a dual hinge physics joint (same as wheel joint)
  79357. */
  79358. var Hinge2Joint = /** @class */ (function (_super) {
  79359. __extends(Hinge2Joint, _super);
  79360. function Hinge2Joint(jointData) {
  79361. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  79362. }
  79363. /**
  79364. * Set the motor values.
  79365. * Attention, this function is plugin specific. Engines won't react 100% the same.
  79366. * @param {number} force the force to apply
  79367. * @param {number} maxForce max force for this motor.
  79368. * @param {motorIndex} the motor's index, 0 or 1.
  79369. */
  79370. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  79371. if (motorIndex === void 0) { motorIndex = 0; }
  79372. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  79373. };
  79374. /**
  79375. * Set the motor limits.
  79376. * Attention, this function is plugin specific. Engines won't react 100% the same.
  79377. * @param {number} upperLimit the upper limit
  79378. * @param {number} lowerLimit lower limit
  79379. * @param {motorIndex} the motor's index, 0 or 1.
  79380. */
  79381. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  79382. if (motorIndex === void 0) { motorIndex = 0; }
  79383. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  79384. };
  79385. return Hinge2Joint;
  79386. }(MotorEnabledJoint));
  79387. BABYLON.Hinge2Joint = Hinge2Joint;
  79388. })(BABYLON || (BABYLON = {}));
  79389. //# sourceMappingURL=babylon.physicsJoint.js.map
  79390. "use strict";
  79391. var BABYLON;
  79392. (function (BABYLON) {
  79393. var PhysicsImpostor = /** @class */ (function () {
  79394. function PhysicsImpostor(object, type, _options, _scene) {
  79395. if (_options === void 0) { _options = { mass: 0 }; }
  79396. var _this = this;
  79397. this.object = object;
  79398. this.type = type;
  79399. this._options = _options;
  79400. this._scene = _scene;
  79401. this._bodyUpdateRequired = false;
  79402. this._onBeforePhysicsStepCallbacks = new Array();
  79403. this._onAfterPhysicsStepCallbacks = new Array();
  79404. this._onPhysicsCollideCallbacks = [];
  79405. this._deltaPosition = BABYLON.Vector3.Zero();
  79406. this._isDisposed = false;
  79407. //temp variables for parent rotation calculations
  79408. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  79409. this._tmpQuat = new BABYLON.Quaternion();
  79410. this._tmpQuat2 = new BABYLON.Quaternion();
  79411. /**
  79412. * this function is executed by the physics engine.
  79413. */
  79414. this.beforeStep = function () {
  79415. if (!_this._physicsEngine) {
  79416. return;
  79417. }
  79418. _this.object.translate(_this._deltaPosition, -1);
  79419. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  79420. _this.object.computeWorldMatrix(false);
  79421. if (_this.object.parent && _this.object.rotationQuaternion) {
  79422. _this.getParentsRotation();
  79423. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  79424. }
  79425. else {
  79426. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  79427. }
  79428. if (!_this._options.disableBidirectionalTransformation) {
  79429. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  79430. }
  79431. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  79432. func(_this);
  79433. });
  79434. };
  79435. /**
  79436. * this function is executed by the physics engine.
  79437. */
  79438. this.afterStep = function () {
  79439. if (!_this._physicsEngine) {
  79440. return;
  79441. }
  79442. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  79443. func(_this);
  79444. });
  79445. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  79446. // object has now its world rotation. needs to be converted to local.
  79447. if (_this.object.parent && _this.object.rotationQuaternion) {
  79448. _this.getParentsRotation();
  79449. _this._tmpQuat.conjugateInPlace();
  79450. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  79451. }
  79452. // take the position set and make it the absolute position of this object.
  79453. _this.object.setAbsolutePosition(_this.object.position);
  79454. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  79455. _this.object.translate(_this._deltaPosition, 1);
  79456. };
  79457. /**
  79458. * Legacy collision detection event support
  79459. */
  79460. this.onCollideEvent = null;
  79461. //event and body object due to cannon's event-based architecture.
  79462. this.onCollide = function (e) {
  79463. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  79464. return;
  79465. }
  79466. if (!_this._physicsEngine) {
  79467. return;
  79468. }
  79469. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  79470. if (otherImpostor) {
  79471. // Legacy collision detection event support
  79472. if (_this.onCollideEvent) {
  79473. _this.onCollideEvent(_this, otherImpostor);
  79474. }
  79475. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  79476. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  79477. }).forEach(function (obj) {
  79478. obj.callback(_this, otherImpostor);
  79479. });
  79480. }
  79481. };
  79482. //sanity check!
  79483. if (!this.object) {
  79484. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  79485. return;
  79486. }
  79487. //legacy support for old syntax.
  79488. if (!this._scene && object.getScene) {
  79489. this._scene = object.getScene();
  79490. }
  79491. if (!this._scene) {
  79492. return;
  79493. }
  79494. this._physicsEngine = this._scene.getPhysicsEngine();
  79495. if (!this._physicsEngine) {
  79496. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  79497. }
  79498. else {
  79499. //set the object's quaternion, if not set
  79500. if (!this.object.rotationQuaternion) {
  79501. if (this.object.rotation) {
  79502. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  79503. }
  79504. else {
  79505. this.object.rotationQuaternion = new BABYLON.Quaternion();
  79506. }
  79507. }
  79508. //default options params
  79509. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  79510. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  79511. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  79512. this._joints = [];
  79513. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  79514. if (!this.object.parent || this._options.ignoreParent) {
  79515. this._init();
  79516. }
  79517. else if (this.object.parent.physicsImpostor) {
  79518. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  79519. }
  79520. }
  79521. }
  79522. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  79523. get: function () {
  79524. return this._isDisposed;
  79525. },
  79526. enumerable: true,
  79527. configurable: true
  79528. });
  79529. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  79530. get: function () {
  79531. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  79532. },
  79533. set: function (value) {
  79534. this.setMass(value);
  79535. },
  79536. enumerable: true,
  79537. configurable: true
  79538. });
  79539. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  79540. get: function () {
  79541. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  79542. },
  79543. set: function (value) {
  79544. if (!this._physicsEngine) {
  79545. return;
  79546. }
  79547. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  79548. },
  79549. enumerable: true,
  79550. configurable: true
  79551. });
  79552. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  79553. get: function () {
  79554. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  79555. },
  79556. set: function (value) {
  79557. if (!this._physicsEngine) {
  79558. return;
  79559. }
  79560. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  79561. },
  79562. enumerable: true,
  79563. configurable: true
  79564. });
  79565. /**
  79566. * This function will completly initialize this impostor.
  79567. * It will create a new body - but only if this mesh has no parent.
  79568. * If it has, this impostor will not be used other than to define the impostor
  79569. * of the child mesh.
  79570. */
  79571. PhysicsImpostor.prototype._init = function () {
  79572. if (!this._physicsEngine) {
  79573. return;
  79574. }
  79575. this._physicsEngine.removeImpostor(this);
  79576. this.physicsBody = null;
  79577. this._parent = this._parent || this._getPhysicsParent();
  79578. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  79579. this._physicsEngine.addImpostor(this);
  79580. }
  79581. };
  79582. PhysicsImpostor.prototype._getPhysicsParent = function () {
  79583. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  79584. var parentMesh = this.object.parent;
  79585. return parentMesh.physicsImpostor;
  79586. }
  79587. return null;
  79588. };
  79589. /**
  79590. * Should a new body be generated.
  79591. */
  79592. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  79593. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  79594. };
  79595. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  79596. this.forceUpdate();
  79597. };
  79598. /**
  79599. * Force a regeneration of this or the parent's impostor's body.
  79600. * Use under cautious - This will remove all joints already implemented.
  79601. */
  79602. PhysicsImpostor.prototype.forceUpdate = function () {
  79603. this._init();
  79604. if (this.parent && !this._options.ignoreParent) {
  79605. this.parent.forceUpdate();
  79606. }
  79607. };
  79608. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  79609. /*public get mesh(): AbstractMesh {
  79610. return this._mesh;
  79611. }*/
  79612. /**
  79613. * Gets the body that holds this impostor. Either its own, or its parent.
  79614. */
  79615. get: function () {
  79616. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  79617. },
  79618. /**
  79619. * Set the physics body. Used mainly by the physics engine/plugin
  79620. */
  79621. set: function (physicsBody) {
  79622. if (this._physicsBody && this._physicsEngine) {
  79623. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  79624. }
  79625. this._physicsBody = physicsBody;
  79626. this.resetUpdateFlags();
  79627. },
  79628. enumerable: true,
  79629. configurable: true
  79630. });
  79631. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  79632. get: function () {
  79633. return !this._options.ignoreParent && this._parent ? this._parent : null;
  79634. },
  79635. set: function (value) {
  79636. this._parent = value;
  79637. },
  79638. enumerable: true,
  79639. configurable: true
  79640. });
  79641. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  79642. this._bodyUpdateRequired = false;
  79643. };
  79644. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  79645. if (this.object.getBoundingInfo) {
  79646. var q = this.object.rotationQuaternion;
  79647. //reset rotation
  79648. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  79649. //calculate the world matrix with no rotation
  79650. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  79651. var boundingInfo = this.object.getBoundingInfo();
  79652. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  79653. //bring back the rotation
  79654. this.object.rotationQuaternion = q;
  79655. //calculate the world matrix with the new rotation
  79656. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  79657. return size;
  79658. }
  79659. else {
  79660. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  79661. }
  79662. };
  79663. PhysicsImpostor.prototype.getObjectCenter = function () {
  79664. if (this.object.getBoundingInfo) {
  79665. var boundingInfo = this.object.getBoundingInfo();
  79666. return boundingInfo.boundingBox.centerWorld;
  79667. }
  79668. else {
  79669. return this.object.position;
  79670. }
  79671. };
  79672. /**
  79673. * Get a specific parametes from the options parameter.
  79674. */
  79675. PhysicsImpostor.prototype.getParam = function (paramName) {
  79676. return this._options[paramName];
  79677. };
  79678. /**
  79679. * Sets a specific parameter in the options given to the physics plugin
  79680. */
  79681. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  79682. this._options[paramName] = value;
  79683. this._bodyUpdateRequired = true;
  79684. };
  79685. /**
  79686. * Specifically change the body's mass option. Won't recreate the physics body object
  79687. */
  79688. PhysicsImpostor.prototype.setMass = function (mass) {
  79689. if (this.getParam("mass") !== mass) {
  79690. this.setParam("mass", mass);
  79691. }
  79692. if (this._physicsEngine) {
  79693. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  79694. }
  79695. };
  79696. PhysicsImpostor.prototype.getLinearVelocity = function () {
  79697. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  79698. };
  79699. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  79700. if (this._physicsEngine) {
  79701. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  79702. }
  79703. };
  79704. PhysicsImpostor.prototype.getAngularVelocity = function () {
  79705. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  79706. };
  79707. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  79708. if (this._physicsEngine) {
  79709. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  79710. }
  79711. };
  79712. /**
  79713. * Execute a function with the physics plugin native code.
  79714. * Provide a function the will have two variables - the world object and the physics body object.
  79715. */
  79716. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  79717. if (this._physicsEngine) {
  79718. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  79719. }
  79720. };
  79721. /**
  79722. * Register a function that will be executed before the physics world is stepping forward.
  79723. */
  79724. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  79725. this._onBeforePhysicsStepCallbacks.push(func);
  79726. };
  79727. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  79728. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  79729. if (index > -1) {
  79730. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  79731. }
  79732. else {
  79733. BABYLON.Tools.Warn("Function to remove was not found");
  79734. }
  79735. };
  79736. /**
  79737. * Register a function that will be executed after the physics step
  79738. */
  79739. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  79740. this._onAfterPhysicsStepCallbacks.push(func);
  79741. };
  79742. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  79743. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  79744. if (index > -1) {
  79745. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  79746. }
  79747. else {
  79748. BABYLON.Tools.Warn("Function to remove was not found");
  79749. }
  79750. };
  79751. /**
  79752. * register a function that will be executed when this impostor collides against a different body.
  79753. */
  79754. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  79755. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  79756. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  79757. };
  79758. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  79759. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  79760. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  79761. if (index > -1) {
  79762. this._onPhysicsCollideCallbacks.splice(index, 1);
  79763. }
  79764. else {
  79765. BABYLON.Tools.Warn("Function to remove was not found");
  79766. }
  79767. };
  79768. PhysicsImpostor.prototype.getParentsRotation = function () {
  79769. var parent = this.object.parent;
  79770. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  79771. while (parent) {
  79772. if (parent.rotationQuaternion) {
  79773. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  79774. }
  79775. else {
  79776. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  79777. }
  79778. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  79779. parent = parent.parent;
  79780. }
  79781. return this._tmpQuat;
  79782. };
  79783. /**
  79784. * Apply a force
  79785. */
  79786. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  79787. if (this._physicsEngine) {
  79788. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  79789. }
  79790. return this;
  79791. };
  79792. /**
  79793. * Apply an impulse
  79794. */
  79795. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  79796. if (this._physicsEngine) {
  79797. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  79798. }
  79799. return this;
  79800. };
  79801. /**
  79802. * A help function to create a joint.
  79803. */
  79804. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  79805. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  79806. this.addJoint(otherImpostor, joint);
  79807. return this;
  79808. };
  79809. /**
  79810. * Add a joint to this impostor with a different impostor.
  79811. */
  79812. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  79813. this._joints.push({
  79814. otherImpostor: otherImpostor,
  79815. joint: joint
  79816. });
  79817. if (this._physicsEngine) {
  79818. this._physicsEngine.addJoint(this, otherImpostor, joint);
  79819. }
  79820. return this;
  79821. };
  79822. /**
  79823. * Will keep this body still, in a sleep mode.
  79824. */
  79825. PhysicsImpostor.prototype.sleep = function () {
  79826. if (this._physicsEngine) {
  79827. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  79828. }
  79829. return this;
  79830. };
  79831. /**
  79832. * Wake the body up.
  79833. */
  79834. PhysicsImpostor.prototype.wakeUp = function () {
  79835. if (this._physicsEngine) {
  79836. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  79837. }
  79838. return this;
  79839. };
  79840. PhysicsImpostor.prototype.clone = function (newObject) {
  79841. if (!newObject)
  79842. return null;
  79843. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  79844. };
  79845. PhysicsImpostor.prototype.dispose = function () {
  79846. var _this = this;
  79847. //no dispose if no physics engine is available.
  79848. if (!this._physicsEngine) {
  79849. return;
  79850. }
  79851. this._joints.forEach(function (j) {
  79852. if (_this._physicsEngine) {
  79853. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  79854. }
  79855. });
  79856. //dispose the physics body
  79857. this._physicsEngine.removeImpostor(this);
  79858. if (this.parent) {
  79859. this.parent.forceUpdate();
  79860. }
  79861. else {
  79862. /*this._object.getChildMeshes().forEach(function(mesh) {
  79863. if (mesh.physicsImpostor) {
  79864. if (disposeChildren) {
  79865. mesh.physicsImpostor.dispose();
  79866. mesh.physicsImpostor = null;
  79867. }
  79868. }
  79869. })*/
  79870. }
  79871. this._isDisposed = true;
  79872. };
  79873. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  79874. this._deltaPosition.copyFrom(position);
  79875. };
  79876. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  79877. if (!this._deltaRotation) {
  79878. this._deltaRotation = new BABYLON.Quaternion();
  79879. }
  79880. this._deltaRotation.copyFrom(rotation);
  79881. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  79882. };
  79883. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  79884. if (this._physicsEngine) {
  79885. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  79886. }
  79887. return this;
  79888. };
  79889. PhysicsImpostor.prototype.getRadius = function () {
  79890. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  79891. };
  79892. /**
  79893. * Sync a bone with this impostor
  79894. * @param bone The bone to sync to the impostor.
  79895. * @param boneMesh The mesh that the bone is influencing.
  79896. * @param jointPivot The pivot of the joint / bone in local space.
  79897. * @param distToJoint Optional distance from the impostor to the joint.
  79898. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  79899. */
  79900. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  79901. var tempVec = PhysicsImpostor._tmpVecs[0];
  79902. var mesh = this.object;
  79903. if (mesh.rotationQuaternion) {
  79904. if (adjustRotation) {
  79905. var tempQuat = PhysicsImpostor._tmpQuat;
  79906. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  79907. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  79908. }
  79909. else {
  79910. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  79911. }
  79912. }
  79913. tempVec.x = 0;
  79914. tempVec.y = 0;
  79915. tempVec.z = 0;
  79916. if (jointPivot) {
  79917. tempVec.x = jointPivot.x;
  79918. tempVec.y = jointPivot.y;
  79919. tempVec.z = jointPivot.z;
  79920. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  79921. if (distToJoint === undefined || distToJoint === null) {
  79922. distToJoint = jointPivot.length();
  79923. }
  79924. tempVec.x *= distToJoint;
  79925. tempVec.y *= distToJoint;
  79926. tempVec.z *= distToJoint;
  79927. }
  79928. if (bone.getParent()) {
  79929. tempVec.addInPlace(mesh.getAbsolutePosition());
  79930. bone.setAbsolutePosition(tempVec, boneMesh);
  79931. }
  79932. else {
  79933. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  79934. boneMesh.position.x -= tempVec.x;
  79935. boneMesh.position.y -= tempVec.y;
  79936. boneMesh.position.z -= tempVec.z;
  79937. }
  79938. };
  79939. /**
  79940. * Sync impostor to a bone
  79941. * @param bone The bone that the impostor will be synced to.
  79942. * @param boneMesh The mesh that the bone is influencing.
  79943. * @param jointPivot The pivot of the joint / bone in local space.
  79944. * @param distToJoint Optional distance from the impostor to the joint.
  79945. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  79946. * @param boneAxis Optional vector3 axis the bone is aligned with
  79947. */
  79948. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  79949. var mesh = this.object;
  79950. if (mesh.rotationQuaternion) {
  79951. if (adjustRotation) {
  79952. var tempQuat = PhysicsImpostor._tmpQuat;
  79953. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  79954. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  79955. }
  79956. else {
  79957. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  79958. }
  79959. }
  79960. var pos = PhysicsImpostor._tmpVecs[0];
  79961. var boneDir = PhysicsImpostor._tmpVecs[1];
  79962. if (!boneAxis) {
  79963. boneAxis = PhysicsImpostor._tmpVecs[2];
  79964. boneAxis.x = 0;
  79965. boneAxis.y = 1;
  79966. boneAxis.z = 0;
  79967. }
  79968. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  79969. bone.getAbsolutePositionToRef(boneMesh, pos);
  79970. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  79971. distToJoint = jointPivot.length();
  79972. }
  79973. if (distToJoint !== undefined && distToJoint !== null) {
  79974. pos.x += boneDir.x * distToJoint;
  79975. pos.y += boneDir.y * distToJoint;
  79976. pos.z += boneDir.z * distToJoint;
  79977. }
  79978. mesh.setAbsolutePosition(pos);
  79979. };
  79980. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  79981. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  79982. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79983. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  79984. //Impostor types
  79985. PhysicsImpostor.NoImpostor = 0;
  79986. PhysicsImpostor.SphereImpostor = 1;
  79987. PhysicsImpostor.BoxImpostor = 2;
  79988. PhysicsImpostor.PlaneImpostor = 3;
  79989. PhysicsImpostor.MeshImpostor = 4;
  79990. PhysicsImpostor.CylinderImpostor = 7;
  79991. PhysicsImpostor.ParticleImpostor = 8;
  79992. PhysicsImpostor.HeightmapImpostor = 9;
  79993. return PhysicsImpostor;
  79994. }());
  79995. BABYLON.PhysicsImpostor = PhysicsImpostor;
  79996. })(BABYLON || (BABYLON = {}));
  79997. //# sourceMappingURL=babylon.physicsImpostor.js.map
  79998. "use strict";
  79999. var BABYLON;
  80000. (function (BABYLON) {
  80001. var PhysicsEngine = /** @class */ (function () {
  80002. function PhysicsEngine(gravity, _physicsPlugin) {
  80003. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  80004. this._physicsPlugin = _physicsPlugin;
  80005. //new methods and parameters
  80006. this._impostors = [];
  80007. this._joints = [];
  80008. if (!this._physicsPlugin.isSupported()) {
  80009. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  80010. + "Please make sure it is included.");
  80011. }
  80012. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  80013. this.setGravity(gravity);
  80014. this.setTimeStep();
  80015. }
  80016. PhysicsEngine.prototype.setGravity = function (gravity) {
  80017. this.gravity = gravity;
  80018. this._physicsPlugin.setGravity(this.gravity);
  80019. };
  80020. /**
  80021. * Set the time step of the physics engine.
  80022. * default is 1/60.
  80023. * To slow it down, enter 1/600 for example.
  80024. * To speed it up, 1/30
  80025. * @param {number} newTimeStep the new timestep to apply to this world.
  80026. */
  80027. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  80028. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  80029. this._physicsPlugin.setTimeStep(newTimeStep);
  80030. };
  80031. /**
  80032. * Get the time step of the physics engine.
  80033. */
  80034. PhysicsEngine.prototype.getTimeStep = function () {
  80035. return this._physicsPlugin.getTimeStep();
  80036. };
  80037. PhysicsEngine.prototype.dispose = function () {
  80038. this._impostors.forEach(function (impostor) {
  80039. impostor.dispose();
  80040. });
  80041. this._physicsPlugin.dispose();
  80042. };
  80043. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  80044. return this._physicsPlugin.name;
  80045. };
  80046. /**
  80047. * Adding a new impostor for the impostor tracking.
  80048. * This will be done by the impostor itself.
  80049. * @param {PhysicsImpostor} impostor the impostor to add
  80050. */
  80051. PhysicsEngine.prototype.addImpostor = function (impostor) {
  80052. impostor.uniqueId = this._impostors.push(impostor);
  80053. //if no parent, generate the body
  80054. if (!impostor.parent) {
  80055. this._physicsPlugin.generatePhysicsBody(impostor);
  80056. }
  80057. };
  80058. /**
  80059. * Remove an impostor from the engine.
  80060. * This impostor and its mesh will not longer be updated by the physics engine.
  80061. * @param {PhysicsImpostor} impostor the impostor to remove
  80062. */
  80063. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  80064. var index = this._impostors.indexOf(impostor);
  80065. if (index > -1) {
  80066. var removed = this._impostors.splice(index, 1);
  80067. //Is it needed?
  80068. if (removed.length) {
  80069. //this will also remove it from the world.
  80070. removed[0].physicsBody = null;
  80071. }
  80072. }
  80073. };
  80074. /**
  80075. * Add a joint to the physics engine
  80076. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  80077. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  80078. * @param {PhysicsJoint} the joint that will connect both impostors.
  80079. */
  80080. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  80081. var impostorJoint = {
  80082. mainImpostor: mainImpostor,
  80083. connectedImpostor: connectedImpostor,
  80084. joint: joint
  80085. };
  80086. joint.physicsPlugin = this._physicsPlugin;
  80087. this._joints.push(impostorJoint);
  80088. this._physicsPlugin.generateJoint(impostorJoint);
  80089. };
  80090. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  80091. var matchingJoints = this._joints.filter(function (impostorJoint) {
  80092. return (impostorJoint.connectedImpostor === connectedImpostor
  80093. && impostorJoint.joint === joint
  80094. && impostorJoint.mainImpostor === mainImpostor);
  80095. });
  80096. if (matchingJoints.length) {
  80097. this._physicsPlugin.removeJoint(matchingJoints[0]);
  80098. //TODO remove it from the list as well
  80099. }
  80100. };
  80101. /**
  80102. * Called by the scene. no need to call it.
  80103. */
  80104. PhysicsEngine.prototype._step = function (delta) {
  80105. var _this = this;
  80106. //check if any mesh has no body / requires an update
  80107. this._impostors.forEach(function (impostor) {
  80108. if (impostor.isBodyInitRequired()) {
  80109. _this._physicsPlugin.generatePhysicsBody(impostor);
  80110. }
  80111. });
  80112. if (delta > 0.1) {
  80113. delta = 0.1;
  80114. }
  80115. else if (delta <= 0) {
  80116. delta = 1.0 / 60.0;
  80117. }
  80118. this._physicsPlugin.executeStep(delta, this._impostors);
  80119. };
  80120. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  80121. return this._physicsPlugin;
  80122. };
  80123. PhysicsEngine.prototype.getImpostors = function () {
  80124. return this._impostors;
  80125. };
  80126. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  80127. for (var i = 0; i < this._impostors.length; ++i) {
  80128. if (this._impostors[i].object === object) {
  80129. return this._impostors[i];
  80130. }
  80131. }
  80132. return null;
  80133. };
  80134. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  80135. for (var i = 0; i < this._impostors.length; ++i) {
  80136. if (this._impostors[i].physicsBody === body) {
  80137. return this._impostors[i];
  80138. }
  80139. }
  80140. return null;
  80141. };
  80142. // Statics
  80143. PhysicsEngine.Epsilon = 0.001;
  80144. return PhysicsEngine;
  80145. }());
  80146. BABYLON.PhysicsEngine = PhysicsEngine;
  80147. })(BABYLON || (BABYLON = {}));
  80148. //# sourceMappingURL=babylon.physicsEngine.js.map
  80149. "use strict";
  80150. var BABYLON;
  80151. (function (BABYLON) {
  80152. var PhysicsHelper = /** @class */ (function () {
  80153. function PhysicsHelper(scene) {
  80154. this._scene = scene;
  80155. this._physicsEngine = this._scene.getPhysicsEngine();
  80156. if (!this._physicsEngine) {
  80157. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  80158. }
  80159. }
  80160. /**
  80161. * @param {Vector3} origin the origin of the explosion
  80162. * @param {number} radius the explosion radius
  80163. * @param {number} strength the explosion strength
  80164. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  80165. */
  80166. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  80167. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  80168. if (!this._physicsEngine) {
  80169. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  80170. return null;
  80171. }
  80172. var impostors = this._physicsEngine.getImpostors();
  80173. if (impostors.length === 0) {
  80174. return null;
  80175. }
  80176. var event = new PhysicsRadialExplosionEvent(this._scene);
  80177. impostors.forEach(function (impostor) {
  80178. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  80179. if (!impostorForceAndContactPoint) {
  80180. return;
  80181. }
  80182. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  80183. });
  80184. event.dispose(false);
  80185. return event;
  80186. };
  80187. /**
  80188. * @param {Vector3} origin the origin of the explosion
  80189. * @param {number} radius the explosion radius
  80190. * @param {number} strength the explosion strength
  80191. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  80192. */
  80193. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  80194. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  80195. if (!this._physicsEngine) {
  80196. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  80197. return null;
  80198. }
  80199. var impostors = this._physicsEngine.getImpostors();
  80200. if (impostors.length === 0) {
  80201. return null;
  80202. }
  80203. var event = new PhysicsRadialExplosionEvent(this._scene);
  80204. impostors.forEach(function (impostor) {
  80205. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  80206. if (!impostorForceAndContactPoint) {
  80207. return;
  80208. }
  80209. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  80210. });
  80211. event.dispose(false);
  80212. return event;
  80213. };
  80214. /**
  80215. * @param {Vector3} origin the origin of the explosion
  80216. * @param {number} radius the explosion radius
  80217. * @param {number} strength the explosion strength
  80218. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  80219. */
  80220. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  80221. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  80222. if (!this._physicsEngine) {
  80223. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  80224. return null;
  80225. }
  80226. var impostors = this._physicsEngine.getImpostors();
  80227. if (impostors.length === 0) {
  80228. return null;
  80229. }
  80230. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  80231. event.dispose(false);
  80232. return event;
  80233. };
  80234. /**
  80235. * @param {Vector3} origin the origin of the updraft
  80236. * @param {number} radius the radius of the updraft
  80237. * @param {number} strength the strength of the updraft
  80238. * @param {number} height the height of the updraft
  80239. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  80240. */
  80241. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  80242. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  80243. if (!this._physicsEngine) {
  80244. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  80245. return null;
  80246. }
  80247. if (this._physicsEngine.getImpostors().length === 0) {
  80248. return null;
  80249. }
  80250. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  80251. event.dispose(false);
  80252. return event;
  80253. };
  80254. /**
  80255. * @param {Vector3} origin the of the vortex
  80256. * @param {number} radius the radius of the vortex
  80257. * @param {number} strength the strength of the vortex
  80258. * @param {number} height the height of the vortex
  80259. */
  80260. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  80261. if (!this._physicsEngine) {
  80262. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  80263. return null;
  80264. }
  80265. if (this._physicsEngine.getImpostors().length === 0) {
  80266. return null;
  80267. }
  80268. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  80269. event.dispose(false);
  80270. return event;
  80271. };
  80272. return PhysicsHelper;
  80273. }());
  80274. BABYLON.PhysicsHelper = PhysicsHelper;
  80275. /***** Radial explosion *****/
  80276. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  80277. function PhysicsRadialExplosionEvent(scene) {
  80278. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  80279. this._rays = [];
  80280. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  80281. this._scene = scene;
  80282. }
  80283. /**
  80284. * Returns the data related to the radial explosion event (sphere & rays).
  80285. * @returns {PhysicsRadialExplosionEventData}
  80286. */
  80287. PhysicsRadialExplosionEvent.prototype.getData = function () {
  80288. this._dataFetched = true;
  80289. return {
  80290. sphere: this._sphere,
  80291. rays: this._rays,
  80292. };
  80293. };
  80294. /**
  80295. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  80296. * @param impostor
  80297. * @param {Vector3} origin the origin of the explosion
  80298. * @param {number} radius the explosion radius
  80299. * @param {number} strength the explosion strength
  80300. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  80301. * @returns {Nullable<PhysicsForceAndContactPoint>}
  80302. */
  80303. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  80304. if (impostor.mass === 0) {
  80305. return null;
  80306. }
  80307. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  80308. return null;
  80309. }
  80310. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  80311. return null;
  80312. }
  80313. var impostorObjectCenter = impostor.getObjectCenter();
  80314. var direction = impostorObjectCenter.subtract(origin);
  80315. var ray = new BABYLON.Ray(origin, direction, radius);
  80316. this._rays.push(ray);
  80317. var hit = ray.intersectsMesh(impostor.object);
  80318. var contactPoint = hit.pickedPoint;
  80319. if (!contactPoint) {
  80320. return null;
  80321. }
  80322. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  80323. if (distanceFromOrigin > radius) {
  80324. return null;
  80325. }
  80326. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  80327. ? strength
  80328. : strength * (1 - (distanceFromOrigin / radius));
  80329. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  80330. return { force: force, contactPoint: contactPoint };
  80331. };
  80332. /**
  80333. * Disposes the sphere.
  80334. * @param {bolean} force
  80335. */
  80336. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  80337. var _this = this;
  80338. if (force === void 0) { force = true; }
  80339. if (force) {
  80340. this._sphere.dispose();
  80341. }
  80342. else {
  80343. setTimeout(function () {
  80344. if (!_this._dataFetched) {
  80345. _this._sphere.dispose();
  80346. }
  80347. }, 0);
  80348. }
  80349. };
  80350. /*** Helpers ***/
  80351. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  80352. if (!this._sphere) {
  80353. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  80354. this._sphere.isVisible = false;
  80355. }
  80356. };
  80357. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  80358. var impostorObject = impostor.object;
  80359. this._prepareSphere();
  80360. this._sphere.position = origin;
  80361. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  80362. this._sphere._updateBoundingInfo();
  80363. this._sphere.computeWorldMatrix(true);
  80364. return this._sphere.intersectsMesh(impostorObject, true);
  80365. };
  80366. return PhysicsRadialExplosionEvent;
  80367. }());
  80368. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  80369. /***** Gravitational Field *****/
  80370. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  80371. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  80372. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  80373. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  80374. this._physicsHelper = physicsHelper;
  80375. this._scene = scene;
  80376. this._origin = origin;
  80377. this._radius = radius;
  80378. this._strength = strength;
  80379. this._falloff = falloff;
  80380. this._tickCallback = this._tick.bind(this);
  80381. }
  80382. /**
  80383. * Returns the data related to the gravitational field event (sphere).
  80384. * @returns {PhysicsGravitationalFieldEventData}
  80385. */
  80386. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  80387. this._dataFetched = true;
  80388. return {
  80389. sphere: this._sphere,
  80390. };
  80391. };
  80392. /**
  80393. * Enables the gravitational field.
  80394. */
  80395. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  80396. this._tickCallback.call(this);
  80397. this._scene.registerBeforeRender(this._tickCallback);
  80398. };
  80399. /**
  80400. * Disables the gravitational field.
  80401. */
  80402. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  80403. this._scene.unregisterBeforeRender(this._tickCallback);
  80404. };
  80405. /**
  80406. * Disposes the sphere.
  80407. * @param {bolean} force
  80408. */
  80409. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  80410. var _this = this;
  80411. if (force === void 0) { force = true; }
  80412. if (force) {
  80413. this._sphere.dispose();
  80414. }
  80415. else {
  80416. setTimeout(function () {
  80417. if (!_this._dataFetched) {
  80418. _this._sphere.dispose();
  80419. }
  80420. }, 0);
  80421. }
  80422. };
  80423. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  80424. // Since the params won't change, we fetch the event only once
  80425. if (this._sphere) {
  80426. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  80427. }
  80428. else {
  80429. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  80430. if (radialExplosionEvent) {
  80431. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  80432. }
  80433. }
  80434. };
  80435. return PhysicsGravitationalFieldEvent;
  80436. }());
  80437. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  80438. /***** Updraft *****/
  80439. var PhysicsUpdraftEvent = /** @class */ (function () {
  80440. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  80441. this._scene = _scene;
  80442. this._origin = _origin;
  80443. this._radius = _radius;
  80444. this._strength = _strength;
  80445. this._height = _height;
  80446. this._updraftMode = _updraftMode;
  80447. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  80448. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  80449. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  80450. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  80451. this._physicsEngine = this._scene.getPhysicsEngine();
  80452. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  80453. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  80454. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  80455. this._originDirection = this._origin.subtract(this._originTop).normalize();
  80456. }
  80457. this._tickCallback = this._tick.bind(this);
  80458. }
  80459. /**
  80460. * Returns the data related to the updraft event (cylinder).
  80461. * @returns {PhysicsUpdraftEventData}
  80462. */
  80463. PhysicsUpdraftEvent.prototype.getData = function () {
  80464. this._dataFetched = true;
  80465. return {
  80466. cylinder: this._cylinder,
  80467. };
  80468. };
  80469. /**
  80470. * Enables the updraft.
  80471. */
  80472. PhysicsUpdraftEvent.prototype.enable = function () {
  80473. this._tickCallback.call(this);
  80474. this._scene.registerBeforeRender(this._tickCallback);
  80475. };
  80476. /**
  80477. * Disables the cortex.
  80478. */
  80479. PhysicsUpdraftEvent.prototype.disable = function () {
  80480. this._scene.unregisterBeforeRender(this._tickCallback);
  80481. };
  80482. /**
  80483. * Disposes the sphere.
  80484. * @param {bolean} force
  80485. */
  80486. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  80487. var _this = this;
  80488. if (force === void 0) { force = true; }
  80489. if (force) {
  80490. this._cylinder.dispose();
  80491. }
  80492. else {
  80493. setTimeout(function () {
  80494. if (!_this._dataFetched) {
  80495. _this._cylinder.dispose();
  80496. }
  80497. }, 0);
  80498. }
  80499. };
  80500. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  80501. if (impostor.mass === 0) {
  80502. return null;
  80503. }
  80504. if (!this._intersectsWithCylinder(impostor)) {
  80505. return null;
  80506. }
  80507. var impostorObjectCenter = impostor.getObjectCenter();
  80508. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  80509. var direction = this._originDirection;
  80510. }
  80511. else {
  80512. var direction = impostorObjectCenter.subtract(this._originTop);
  80513. }
  80514. var multiplier = this._strength * -1;
  80515. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  80516. return { force: force, contactPoint: impostorObjectCenter };
  80517. };
  80518. PhysicsUpdraftEvent.prototype._tick = function () {
  80519. var _this = this;
  80520. this._physicsEngine.getImpostors().forEach(function (impostor) {
  80521. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  80522. if (!impostorForceAndContactPoint) {
  80523. return;
  80524. }
  80525. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  80526. });
  80527. };
  80528. /*** Helpers ***/
  80529. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  80530. if (!this._cylinder) {
  80531. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  80532. height: this._height,
  80533. diameter: this._radius * 2,
  80534. }, this._scene);
  80535. this._cylinder.isVisible = false;
  80536. }
  80537. };
  80538. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  80539. var impostorObject = impostor.object;
  80540. this._prepareCylinder();
  80541. this._cylinder.position = this._cylinderPosition;
  80542. return this._cylinder.intersectsMesh(impostorObject, true);
  80543. };
  80544. return PhysicsUpdraftEvent;
  80545. }());
  80546. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  80547. /***** Vortex *****/
  80548. var PhysicsVortexEvent = /** @class */ (function () {
  80549. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  80550. this._scene = _scene;
  80551. this._origin = _origin;
  80552. this._radius = _radius;
  80553. this._strength = _strength;
  80554. this._height = _height;
  80555. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  80556. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  80557. this._updraftMultiplier = 0.02;
  80558. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  80559. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  80560. this._physicsEngine = this._scene.getPhysicsEngine();
  80561. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  80562. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  80563. this._tickCallback = this._tick.bind(this);
  80564. }
  80565. /**
  80566. * Returns the data related to the vortex event (cylinder).
  80567. * @returns {PhysicsVortexEventData}
  80568. */
  80569. PhysicsVortexEvent.prototype.getData = function () {
  80570. this._dataFetched = true;
  80571. return {
  80572. cylinder: this._cylinder,
  80573. };
  80574. };
  80575. /**
  80576. * Enables the vortex.
  80577. */
  80578. PhysicsVortexEvent.prototype.enable = function () {
  80579. this._tickCallback.call(this);
  80580. this._scene.registerBeforeRender(this._tickCallback);
  80581. };
  80582. /**
  80583. * Disables the cortex.
  80584. */
  80585. PhysicsVortexEvent.prototype.disable = function () {
  80586. this._scene.unregisterBeforeRender(this._tickCallback);
  80587. };
  80588. /**
  80589. * Disposes the sphere.
  80590. * @param {bolean} force
  80591. */
  80592. PhysicsVortexEvent.prototype.dispose = function (force) {
  80593. var _this = this;
  80594. if (force === void 0) { force = true; }
  80595. if (force) {
  80596. this._cylinder.dispose();
  80597. }
  80598. else {
  80599. setTimeout(function () {
  80600. if (!_this._dataFetched) {
  80601. _this._cylinder.dispose();
  80602. }
  80603. }, 0);
  80604. }
  80605. };
  80606. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  80607. if (impostor.mass === 0) {
  80608. return null;
  80609. }
  80610. if (!this._intersectsWithCylinder(impostor)) {
  80611. return null;
  80612. }
  80613. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  80614. return null;
  80615. }
  80616. var impostorObjectCenter = impostor.getObjectCenter();
  80617. 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)
  80618. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  80619. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  80620. var hit = ray.intersectsMesh(impostor.object);
  80621. var contactPoint = hit.pickedPoint;
  80622. if (!contactPoint) {
  80623. return null;
  80624. }
  80625. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  80626. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  80627. var directionToOrigin = contactPoint.normalize();
  80628. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  80629. directionToOrigin = directionToOrigin.negate();
  80630. }
  80631. // TODO: find a more physically based solution
  80632. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  80633. var forceX = directionToOrigin.x * this._strength / 8;
  80634. var forceY = directionToOrigin.y * this._updraftMultiplier;
  80635. var forceZ = directionToOrigin.z * this._strength / 8;
  80636. }
  80637. else {
  80638. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  80639. var forceY = this._originTop.y * this._updraftMultiplier;
  80640. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  80641. }
  80642. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  80643. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  80644. return { force: force, contactPoint: impostorObjectCenter };
  80645. };
  80646. PhysicsVortexEvent.prototype._tick = function () {
  80647. var _this = this;
  80648. this._physicsEngine.getImpostors().forEach(function (impostor) {
  80649. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  80650. if (!impostorForceAndContactPoint) {
  80651. return;
  80652. }
  80653. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  80654. });
  80655. };
  80656. /*** Helpers ***/
  80657. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  80658. if (!this._cylinder) {
  80659. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  80660. height: this._height,
  80661. diameter: this._radius * 2,
  80662. }, this._scene);
  80663. this._cylinder.isVisible = false;
  80664. }
  80665. };
  80666. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  80667. var impostorObject = impostor.object;
  80668. this._prepareCylinder();
  80669. this._cylinder.position = this._cylinderPosition;
  80670. return this._cylinder.intersectsMesh(impostorObject, true);
  80671. };
  80672. return PhysicsVortexEvent;
  80673. }());
  80674. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  80675. /***** Enums *****/
  80676. /**
  80677. * The strenght of the force in correspondence to the distance of the affected object
  80678. */
  80679. var PhysicsRadialImpulseFalloff;
  80680. (function (PhysicsRadialImpulseFalloff) {
  80681. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  80682. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  80683. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  80684. /**
  80685. * The strenght of the force in correspondence to the distance of the affected object
  80686. */
  80687. var PhysicsUpdraftMode;
  80688. (function (PhysicsUpdraftMode) {
  80689. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  80690. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  80691. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  80692. })(BABYLON || (BABYLON = {}));
  80693. //# sourceMappingURL=babylon.physicsHelper.js.map
  80694. "use strict";
  80695. var BABYLON;
  80696. (function (BABYLON) {
  80697. var CannonJSPlugin = /** @class */ (function () {
  80698. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  80699. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  80700. if (iterations === void 0) { iterations = 10; }
  80701. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  80702. this.name = "CannonJSPlugin";
  80703. this._physicsMaterials = new Array();
  80704. this._fixedTimeStep = 1 / 60;
  80705. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  80706. this.BJSCANNON = CANNON;
  80707. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  80708. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  80709. this._tmpPosition = BABYLON.Vector3.Zero();
  80710. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  80711. this._tmpUnityRotation = new BABYLON.Quaternion();
  80712. if (!this.isSupported()) {
  80713. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  80714. return;
  80715. }
  80716. this._extendNamespace();
  80717. this.world = new this.BJSCANNON.World();
  80718. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  80719. this.world.solver.iterations = iterations;
  80720. }
  80721. CannonJSPlugin.prototype.setGravity = function (gravity) {
  80722. this.world.gravity.copy(gravity);
  80723. };
  80724. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  80725. this._fixedTimeStep = timeStep;
  80726. };
  80727. CannonJSPlugin.prototype.getTimeStep = function () {
  80728. return this._fixedTimeStep;
  80729. };
  80730. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  80731. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  80732. };
  80733. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  80734. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  80735. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  80736. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  80737. };
  80738. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  80739. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  80740. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  80741. impostor.physicsBody.applyForce(impulse, worldPoint);
  80742. };
  80743. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  80744. //parent-child relationship. Does this impostor has a parent impostor?
  80745. if (impostor.parent) {
  80746. if (impostor.physicsBody) {
  80747. this.removePhysicsBody(impostor);
  80748. //TODO is that needed?
  80749. impostor.forceUpdate();
  80750. }
  80751. return;
  80752. }
  80753. //should a new body be created for this impostor?
  80754. if (impostor.isBodyInitRequired()) {
  80755. var shape = this._createShape(impostor);
  80756. //unregister events, if body is being changed
  80757. var oldBody = impostor.physicsBody;
  80758. if (oldBody) {
  80759. this.removePhysicsBody(impostor);
  80760. }
  80761. //create the body and material
  80762. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  80763. var bodyCreationObject = {
  80764. mass: impostor.getParam("mass"),
  80765. material: material
  80766. };
  80767. // A simple extend, in case native options were used.
  80768. var nativeOptions = impostor.getParam("nativeOptions");
  80769. for (var key in nativeOptions) {
  80770. if (nativeOptions.hasOwnProperty(key)) {
  80771. bodyCreationObject[key] = nativeOptions[key];
  80772. }
  80773. }
  80774. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  80775. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  80776. this.world.addEventListener("preStep", impostor.beforeStep);
  80777. this.world.addEventListener("postStep", impostor.afterStep);
  80778. impostor.physicsBody.addShape(shape);
  80779. this.world.add(impostor.physicsBody);
  80780. //try to keep the body moving in the right direction by taking old properties.
  80781. //Should be tested!
  80782. if (oldBody) {
  80783. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  80784. impostor.physicsBody[param].copy(oldBody[param]);
  80785. });
  80786. }
  80787. this._processChildMeshes(impostor);
  80788. }
  80789. //now update the body's transformation
  80790. this._updatePhysicsBodyTransformation(impostor);
  80791. };
  80792. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  80793. var _this = this;
  80794. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  80795. var currentRotation = mainImpostor.object.rotationQuaternion;
  80796. if (meshChildren.length) {
  80797. var processMesh = function (localPosition, mesh) {
  80798. if (!currentRotation || !mesh.rotationQuaternion) {
  80799. return;
  80800. }
  80801. var childImpostor = mesh.getPhysicsImpostor();
  80802. if (childImpostor) {
  80803. var parent = childImpostor.parent;
  80804. if (parent !== mainImpostor) {
  80805. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  80806. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  80807. if (childImpostor.physicsBody) {
  80808. _this.removePhysicsBody(childImpostor);
  80809. childImpostor.physicsBody = null;
  80810. }
  80811. childImpostor.parent = mainImpostor;
  80812. childImpostor.resetUpdateFlags();
  80813. 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));
  80814. //Add the mass of the children.
  80815. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  80816. }
  80817. }
  80818. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  80819. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  80820. };
  80821. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  80822. }
  80823. };
  80824. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  80825. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  80826. this.world.removeEventListener("preStep", impostor.beforeStep);
  80827. this.world.removeEventListener("postStep", impostor.afterStep);
  80828. this.world.remove(impostor.physicsBody);
  80829. };
  80830. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  80831. var mainBody = impostorJoint.mainImpostor.physicsBody;
  80832. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  80833. if (!mainBody || !connectedBody) {
  80834. return;
  80835. }
  80836. var constraint;
  80837. var jointData = impostorJoint.joint.jointData;
  80838. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  80839. var constraintData = {
  80840. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  80841. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  80842. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  80843. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  80844. maxForce: jointData.nativeParams.maxForce,
  80845. collideConnected: !!jointData.collision
  80846. };
  80847. switch (impostorJoint.joint.type) {
  80848. case BABYLON.PhysicsJoint.HingeJoint:
  80849. case BABYLON.PhysicsJoint.Hinge2Joint:
  80850. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  80851. break;
  80852. case BABYLON.PhysicsJoint.DistanceJoint:
  80853. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  80854. break;
  80855. case BABYLON.PhysicsJoint.SpringJoint:
  80856. var springData = jointData;
  80857. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  80858. restLength: springData.length,
  80859. stiffness: springData.stiffness,
  80860. damping: springData.damping,
  80861. localAnchorA: constraintData.pivotA,
  80862. localAnchorB: constraintData.pivotB
  80863. });
  80864. break;
  80865. case BABYLON.PhysicsJoint.LockJoint:
  80866. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  80867. break;
  80868. case BABYLON.PhysicsJoint.PointToPointJoint:
  80869. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  80870. default:
  80871. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  80872. break;
  80873. }
  80874. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  80875. constraint.collideConnected = !!jointData.collision;
  80876. impostorJoint.joint.physicsJoint = constraint;
  80877. //don't add spring as constraint, as it is not one.
  80878. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  80879. this.world.addConstraint(constraint);
  80880. }
  80881. else {
  80882. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  80883. constraint.applyForce();
  80884. });
  80885. }
  80886. };
  80887. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  80888. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  80889. };
  80890. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  80891. var index;
  80892. var mat;
  80893. for (index = 0; index < this._physicsMaterials.length; index++) {
  80894. mat = this._physicsMaterials[index];
  80895. if (mat.friction === friction && mat.restitution === restitution) {
  80896. return mat;
  80897. }
  80898. }
  80899. var currentMat = new this.BJSCANNON.Material(name);
  80900. currentMat.friction = friction;
  80901. currentMat.restitution = restitution;
  80902. this._physicsMaterials.push(currentMat);
  80903. return currentMat;
  80904. };
  80905. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  80906. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  80907. };
  80908. CannonJSPlugin.prototype._createShape = function (impostor) {
  80909. var object = impostor.object;
  80910. var returnValue;
  80911. var extendSize = impostor.getObjectExtendSize();
  80912. switch (impostor.type) {
  80913. case BABYLON.PhysicsImpostor.SphereImpostor:
  80914. var radiusX = extendSize.x;
  80915. var radiusY = extendSize.y;
  80916. var radiusZ = extendSize.z;
  80917. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  80918. break;
  80919. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  80920. case BABYLON.PhysicsImpostor.CylinderImpostor:
  80921. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  80922. break;
  80923. case BABYLON.PhysicsImpostor.BoxImpostor:
  80924. var box = extendSize.scale(0.5);
  80925. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  80926. break;
  80927. case BABYLON.PhysicsImpostor.PlaneImpostor:
  80928. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  80929. returnValue = new this.BJSCANNON.Plane();
  80930. break;
  80931. case BABYLON.PhysicsImpostor.MeshImpostor:
  80932. // should transform the vertex data to world coordinates!!
  80933. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  80934. var rawFaces = object.getIndices ? object.getIndices() : [];
  80935. if (!rawVerts)
  80936. return;
  80937. // get only scale! so the object could transform correctly.
  80938. var oldPosition = object.position.clone();
  80939. var oldRotation = object.rotation && object.rotation.clone();
  80940. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  80941. object.position.copyFromFloats(0, 0, 0);
  80942. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  80943. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  80944. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  80945. var transform = object.computeWorldMatrix(true);
  80946. // convert rawVerts to object space
  80947. var temp = new Array();
  80948. var index;
  80949. for (index = 0; index < rawVerts.length; index += 3) {
  80950. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  80951. }
  80952. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  80953. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  80954. //now set back the transformation!
  80955. object.position.copyFrom(oldPosition);
  80956. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  80957. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  80958. break;
  80959. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  80960. var oldPosition2 = object.position.clone();
  80961. var oldRotation2 = object.rotation && object.rotation.clone();
  80962. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  80963. object.position.copyFromFloats(0, 0, 0);
  80964. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  80965. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  80966. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  80967. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  80968. returnValue = this._createHeightmap(object);
  80969. object.position.copyFrom(oldPosition2);
  80970. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  80971. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  80972. object.computeWorldMatrix(true);
  80973. break;
  80974. case BABYLON.PhysicsImpostor.ParticleImpostor:
  80975. returnValue = new this.BJSCANNON.Particle();
  80976. break;
  80977. }
  80978. return returnValue;
  80979. };
  80980. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  80981. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  80982. var transform = object.computeWorldMatrix(true);
  80983. // convert rawVerts to object space
  80984. var temp = new Array();
  80985. var index;
  80986. for (index = 0; index < pos.length; index += 3) {
  80987. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  80988. }
  80989. pos = temp;
  80990. var matrix = new Array();
  80991. //For now pointDepth will not be used and will be automatically calculated.
  80992. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  80993. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  80994. var boundingInfo = object.getBoundingInfo();
  80995. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  80996. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  80997. var elementSize = dim * 2 / arraySize;
  80998. for (var i = 0; i < pos.length; i = i + 3) {
  80999. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  81000. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  81001. var y = -pos[i + 2] + minY;
  81002. if (!matrix[x]) {
  81003. matrix[x] = [];
  81004. }
  81005. if (!matrix[x][z]) {
  81006. matrix[x][z] = y;
  81007. }
  81008. matrix[x][z] = Math.max(y, matrix[x][z]);
  81009. }
  81010. for (var x = 0; x <= arraySize; ++x) {
  81011. if (!matrix[x]) {
  81012. var loc = 1;
  81013. while (!matrix[(x + loc) % arraySize]) {
  81014. loc++;
  81015. }
  81016. matrix[x] = matrix[(x + loc) % arraySize].slice();
  81017. //console.log("missing x", x);
  81018. }
  81019. for (var z = 0; z <= arraySize; ++z) {
  81020. if (!matrix[x][z]) {
  81021. var loc = 1;
  81022. var newValue;
  81023. while (newValue === undefined) {
  81024. newValue = matrix[x][(z + loc++) % arraySize];
  81025. }
  81026. matrix[x][z] = newValue;
  81027. }
  81028. }
  81029. }
  81030. var shape = new this.BJSCANNON.Heightfield(matrix, {
  81031. elementSize: elementSize
  81032. });
  81033. //For future reference, needed for body transformation
  81034. shape.minY = minY;
  81035. return shape;
  81036. };
  81037. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  81038. var object = impostor.object;
  81039. //make sure it is updated...
  81040. object.computeWorldMatrix && object.computeWorldMatrix(true);
  81041. // The delta between the mesh position and the mesh bounding box center
  81042. var bInfo = object.getBoundingInfo();
  81043. if (!bInfo)
  81044. return;
  81045. var center = impostor.getObjectCenter();
  81046. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  81047. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  81048. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  81049. this._tmpPosition.copyFrom(center);
  81050. var quaternion = object.rotationQuaternion;
  81051. if (!quaternion) {
  81052. return;
  81053. }
  81054. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  81055. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  81056. //-90 DEG in X, precalculated
  81057. quaternion = quaternion.multiply(this._minus90X);
  81058. //Invert! (Precalculated, 90 deg in X)
  81059. //No need to clone. this will never change.
  81060. impostor.setDeltaRotation(this._plus90X);
  81061. }
  81062. //If it is a heightfield, if should be centered.
  81063. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  81064. var mesh = object;
  81065. var boundingInfo = mesh.getBoundingInfo();
  81066. //calculate the correct body position:
  81067. var rotationQuaternion = mesh.rotationQuaternion;
  81068. mesh.rotationQuaternion = this._tmpUnityRotation;
  81069. mesh.computeWorldMatrix(true);
  81070. //get original center with no rotation
  81071. var c = center.clone();
  81072. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  81073. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  81074. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  81075. mesh.setPreTransformMatrix(p);
  81076. mesh.computeWorldMatrix(true);
  81077. //calculate the translation
  81078. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  81079. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  81080. //add it inverted to the delta
  81081. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  81082. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  81083. //rotation is back
  81084. mesh.rotationQuaternion = rotationQuaternion;
  81085. mesh.setPreTransformMatrix(oldPivot);
  81086. mesh.computeWorldMatrix(true);
  81087. }
  81088. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  81089. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  81090. //this._tmpPosition.copyFrom(object.position);
  81091. }
  81092. impostor.setDeltaPosition(this._tmpDeltaPosition);
  81093. //Now update the impostor object
  81094. impostor.physicsBody.position.copy(this._tmpPosition);
  81095. impostor.physicsBody.quaternion.copy(quaternion);
  81096. };
  81097. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  81098. impostor.object.position.copyFrom(impostor.physicsBody.position);
  81099. if (impostor.object.rotationQuaternion) {
  81100. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  81101. }
  81102. };
  81103. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  81104. impostor.physicsBody.position.copy(newPosition);
  81105. impostor.physicsBody.quaternion.copy(newRotation);
  81106. };
  81107. CannonJSPlugin.prototype.isSupported = function () {
  81108. return this.BJSCANNON !== undefined;
  81109. };
  81110. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  81111. impostor.physicsBody.velocity.copy(velocity);
  81112. };
  81113. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  81114. impostor.physicsBody.angularVelocity.copy(velocity);
  81115. };
  81116. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  81117. var v = impostor.physicsBody.velocity;
  81118. if (!v) {
  81119. return null;
  81120. }
  81121. return new BABYLON.Vector3(v.x, v.y, v.z);
  81122. };
  81123. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  81124. var v = impostor.physicsBody.angularVelocity;
  81125. if (!v) {
  81126. return null;
  81127. }
  81128. return new BABYLON.Vector3(v.x, v.y, v.z);
  81129. };
  81130. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  81131. impostor.physicsBody.mass = mass;
  81132. impostor.physicsBody.updateMassProperties();
  81133. };
  81134. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  81135. return impostor.physicsBody.mass;
  81136. };
  81137. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  81138. return impostor.physicsBody.material.friction;
  81139. };
  81140. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  81141. impostor.physicsBody.material.friction = friction;
  81142. };
  81143. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  81144. return impostor.physicsBody.material.restitution;
  81145. };
  81146. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  81147. impostor.physicsBody.material.restitution = restitution;
  81148. };
  81149. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  81150. impostor.physicsBody.sleep();
  81151. };
  81152. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  81153. impostor.physicsBody.wakeUp();
  81154. };
  81155. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  81156. joint.physicsJoint.distance = maxDistance;
  81157. };
  81158. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  81159. // if (!motorIndex) {
  81160. // joint.physicsJoint.enableMotor();
  81161. // }
  81162. // }
  81163. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  81164. // if (!motorIndex) {
  81165. // joint.physicsJoint.disableMotor();
  81166. // }
  81167. // }
  81168. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  81169. if (!motorIndex) {
  81170. joint.physicsJoint.enableMotor();
  81171. joint.physicsJoint.setMotorSpeed(speed);
  81172. if (maxForce) {
  81173. this.setLimit(joint, maxForce);
  81174. }
  81175. }
  81176. };
  81177. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  81178. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  81179. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  81180. };
  81181. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  81182. var body = impostor.physicsBody;
  81183. mesh.position.x = body.position.x;
  81184. mesh.position.y = body.position.y;
  81185. mesh.position.z = body.position.z;
  81186. if (mesh.rotationQuaternion) {
  81187. mesh.rotationQuaternion.x = body.quaternion.x;
  81188. mesh.rotationQuaternion.y = body.quaternion.y;
  81189. mesh.rotationQuaternion.z = body.quaternion.z;
  81190. mesh.rotationQuaternion.w = body.quaternion.w;
  81191. }
  81192. };
  81193. CannonJSPlugin.prototype.getRadius = function (impostor) {
  81194. var shape = impostor.physicsBody.shapes[0];
  81195. return shape.boundingSphereRadius;
  81196. };
  81197. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  81198. var shape = impostor.physicsBody.shapes[0];
  81199. result.x = shape.halfExtents.x * 2;
  81200. result.y = shape.halfExtents.y * 2;
  81201. result.z = shape.halfExtents.z * 2;
  81202. };
  81203. CannonJSPlugin.prototype.dispose = function () {
  81204. };
  81205. CannonJSPlugin.prototype._extendNamespace = function () {
  81206. //this will force cannon to execute at least one step when using interpolation
  81207. var step_tmp1 = new this.BJSCANNON.Vec3();
  81208. var Engine = this.BJSCANNON;
  81209. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  81210. maxSubSteps = maxSubSteps || 10;
  81211. timeSinceLastCalled = timeSinceLastCalled || 0;
  81212. if (timeSinceLastCalled === 0) {
  81213. this.internalStep(dt);
  81214. this.time += dt;
  81215. }
  81216. else {
  81217. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  81218. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  81219. var t0 = performance.now();
  81220. for (var i = 0; i !== internalSteps; i++) {
  81221. this.internalStep(dt);
  81222. if (performance.now() - t0 > dt * 1000) {
  81223. break;
  81224. }
  81225. }
  81226. this.time += timeSinceLastCalled;
  81227. var h = this.time % dt;
  81228. var h_div_dt = h / dt;
  81229. var interpvelo = step_tmp1;
  81230. var bodies = this.bodies;
  81231. for (var j = 0; j !== bodies.length; j++) {
  81232. var b = bodies[j];
  81233. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  81234. b.position.vsub(b.previousPosition, interpvelo);
  81235. interpvelo.scale(h_div_dt, interpvelo);
  81236. b.position.vadd(interpvelo, b.interpolatedPosition);
  81237. }
  81238. else {
  81239. b.interpolatedPosition.copy(b.position);
  81240. b.interpolatedQuaternion.copy(b.quaternion);
  81241. }
  81242. }
  81243. }
  81244. };
  81245. };
  81246. return CannonJSPlugin;
  81247. }());
  81248. BABYLON.CannonJSPlugin = CannonJSPlugin;
  81249. })(BABYLON || (BABYLON = {}));
  81250. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  81251. "use strict";
  81252. var BABYLON;
  81253. (function (BABYLON) {
  81254. var OimoJSPlugin = /** @class */ (function () {
  81255. function OimoJSPlugin(iterations) {
  81256. this.name = "OimoJSPlugin";
  81257. this._tmpImpostorsArray = [];
  81258. this._tmpPositionVector = BABYLON.Vector3.Zero();
  81259. this.BJSOIMO = OIMO;
  81260. this.world = new this.BJSOIMO.World({
  81261. iterations: iterations
  81262. });
  81263. this.world.clear();
  81264. }
  81265. OimoJSPlugin.prototype.setGravity = function (gravity) {
  81266. this.world.gravity.copy(gravity);
  81267. };
  81268. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  81269. this.world.timeStep = timeStep;
  81270. };
  81271. OimoJSPlugin.prototype.getTimeStep = function () {
  81272. return this.world.timeStep;
  81273. };
  81274. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  81275. var _this = this;
  81276. impostors.forEach(function (impostor) {
  81277. impostor.beforeStep();
  81278. });
  81279. this.world.step();
  81280. impostors.forEach(function (impostor) {
  81281. impostor.afterStep();
  81282. //update the ordered impostors array
  81283. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  81284. });
  81285. //check for collisions
  81286. var contact = this.world.contacts;
  81287. while (contact !== null) {
  81288. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  81289. contact = contact.next;
  81290. continue;
  81291. }
  81292. //is this body colliding with any other? get the impostor
  81293. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  81294. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  81295. if (!mainImpostor || !collidingImpostor) {
  81296. contact = contact.next;
  81297. continue;
  81298. }
  81299. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  81300. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  81301. contact = contact.next;
  81302. }
  81303. };
  81304. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  81305. var mass = impostor.physicsBody.mass;
  81306. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  81307. };
  81308. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  81309. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  81310. this.applyImpulse(impostor, force, contactPoint);
  81311. };
  81312. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  81313. var _this = this;
  81314. //parent-child relationship. Does this impostor has a parent impostor?
  81315. if (impostor.parent) {
  81316. if (impostor.physicsBody) {
  81317. this.removePhysicsBody(impostor);
  81318. //TODO is that needed?
  81319. impostor.forceUpdate();
  81320. }
  81321. return;
  81322. }
  81323. if (impostor.isBodyInitRequired()) {
  81324. var bodyConfig = {
  81325. name: impostor.uniqueId,
  81326. //Oimo must have mass, also for static objects.
  81327. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  81328. size: [],
  81329. type: [],
  81330. pos: [],
  81331. posShape: [],
  81332. rot: [],
  81333. rotShape: [],
  81334. move: impostor.getParam("mass") !== 0,
  81335. density: impostor.getParam("mass"),
  81336. friction: impostor.getParam("friction"),
  81337. restitution: impostor.getParam("restitution"),
  81338. //Supporting older versions of Oimo
  81339. world: this.world
  81340. };
  81341. var impostors = [impostor];
  81342. var addToArray = function (parent) {
  81343. if (!parent.getChildMeshes)
  81344. return;
  81345. parent.getChildMeshes().forEach(function (m) {
  81346. if (m.physicsImpostor) {
  81347. impostors.push(m.physicsImpostor);
  81348. //m.physicsImpostor._init();
  81349. }
  81350. });
  81351. };
  81352. addToArray(impostor.object);
  81353. var checkWithEpsilon_1 = function (value) {
  81354. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  81355. };
  81356. impostors.forEach(function (i) {
  81357. if (!i.object.rotationQuaternion) {
  81358. return;
  81359. }
  81360. //get the correct bounding box
  81361. var oldQuaternion = i.object.rotationQuaternion;
  81362. var rot = oldQuaternion.toEulerAngles();
  81363. var extendSize = i.getObjectExtendSize();
  81364. var radToDeg = 57.295779513082320876;
  81365. if (i === impostor) {
  81366. var center = impostor.getObjectCenter();
  81367. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  81368. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  81369. //Can also use Array.prototype.push.apply
  81370. bodyConfig.pos.push(center.x);
  81371. bodyConfig.pos.push(center.y);
  81372. bodyConfig.pos.push(center.z);
  81373. bodyConfig.posShape.push(0, 0, 0);
  81374. //tmp solution
  81375. bodyConfig.rot.push(rot.x * radToDeg);
  81376. bodyConfig.rot.push(rot.y * radToDeg);
  81377. bodyConfig.rot.push(rot.z * radToDeg);
  81378. bodyConfig.rotShape.push(0, 0, 0);
  81379. }
  81380. else {
  81381. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  81382. bodyConfig.posShape.push(localPosition.x);
  81383. bodyConfig.posShape.push(localPosition.y);
  81384. bodyConfig.posShape.push(localPosition.z);
  81385. bodyConfig.pos.push(0, 0, 0);
  81386. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  81387. bodyConfig.rot.push(0);
  81388. bodyConfig.rot.push(0);
  81389. bodyConfig.rot.push(0);
  81390. bodyConfig.rotShape.push(rot.x * radToDeg);
  81391. bodyConfig.rotShape.push(rot.y * radToDeg);
  81392. bodyConfig.rotShape.push(rot.z * radToDeg);
  81393. }
  81394. // register mesh
  81395. switch (i.type) {
  81396. case BABYLON.PhysicsImpostor.ParticleImpostor:
  81397. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  81398. case BABYLON.PhysicsImpostor.SphereImpostor:
  81399. var radiusX = extendSize.x;
  81400. var radiusY = extendSize.y;
  81401. var radiusZ = extendSize.z;
  81402. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  81403. bodyConfig.type.push('sphere');
  81404. //due to the way oimo works with compounds, add 3 times
  81405. bodyConfig.size.push(size);
  81406. bodyConfig.size.push(size);
  81407. bodyConfig.size.push(size);
  81408. break;
  81409. case BABYLON.PhysicsImpostor.CylinderImpostor:
  81410. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  81411. var sizeY = checkWithEpsilon_1(extendSize.y);
  81412. bodyConfig.type.push('cylinder');
  81413. bodyConfig.size.push(sizeX);
  81414. bodyConfig.size.push(sizeY);
  81415. //due to the way oimo works with compounds, add one more value.
  81416. bodyConfig.size.push(sizeY);
  81417. break;
  81418. case BABYLON.PhysicsImpostor.PlaneImpostor:
  81419. case BABYLON.PhysicsImpostor.BoxImpostor:
  81420. default:
  81421. var sizeX = checkWithEpsilon_1(extendSize.x);
  81422. var sizeY = checkWithEpsilon_1(extendSize.y);
  81423. var sizeZ = checkWithEpsilon_1(extendSize.z);
  81424. bodyConfig.type.push('box');
  81425. //if (i === impostor) {
  81426. bodyConfig.size.push(sizeX);
  81427. bodyConfig.size.push(sizeY);
  81428. bodyConfig.size.push(sizeZ);
  81429. //} else {
  81430. // bodyConfig.size.push(0,0,0);
  81431. //}
  81432. break;
  81433. }
  81434. //actually not needed, but hey...
  81435. i.object.rotationQuaternion = oldQuaternion;
  81436. });
  81437. impostor.physicsBody = this.world.add(bodyConfig);
  81438. }
  81439. else {
  81440. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  81441. }
  81442. impostor.setDeltaPosition(this._tmpPositionVector);
  81443. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  81444. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  81445. };
  81446. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  81447. //impostor.physicsBody.dispose();
  81448. //Same as : (older oimo versions)
  81449. this.world.removeRigidBody(impostor.physicsBody);
  81450. };
  81451. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  81452. var mainBody = impostorJoint.mainImpostor.physicsBody;
  81453. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  81454. if (!mainBody || !connectedBody) {
  81455. return;
  81456. }
  81457. var jointData = impostorJoint.joint.jointData;
  81458. var options = jointData.nativeParams || {};
  81459. var type;
  81460. var nativeJointData = {
  81461. body1: mainBody,
  81462. body2: connectedBody,
  81463. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  81464. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  81465. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  81466. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  81467. min: options.min,
  81468. max: options.max,
  81469. collision: options.collision || jointData.collision,
  81470. spring: options.spring,
  81471. //supporting older version of Oimo
  81472. world: this.world
  81473. };
  81474. switch (impostorJoint.joint.type) {
  81475. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  81476. type = "jointBall";
  81477. break;
  81478. case BABYLON.PhysicsJoint.SpringJoint:
  81479. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  81480. var springData = jointData;
  81481. nativeJointData.min = springData.length || nativeJointData.min;
  81482. //Max should also be set, just make sure it is at least min
  81483. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  81484. case BABYLON.PhysicsJoint.DistanceJoint:
  81485. type = "jointDistance";
  81486. nativeJointData.max = jointData.maxDistance;
  81487. break;
  81488. case BABYLON.PhysicsJoint.PrismaticJoint:
  81489. type = "jointPrisme";
  81490. break;
  81491. case BABYLON.PhysicsJoint.SliderJoint:
  81492. type = "jointSlide";
  81493. break;
  81494. case BABYLON.PhysicsJoint.WheelJoint:
  81495. type = "jointWheel";
  81496. break;
  81497. case BABYLON.PhysicsJoint.HingeJoint:
  81498. default:
  81499. type = "jointHinge";
  81500. break;
  81501. }
  81502. nativeJointData.type = type;
  81503. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  81504. };
  81505. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  81506. //Bug in Oimo prevents us from disposing a joint in the playground
  81507. //joint.joint.physicsJoint.dispose();
  81508. //So we will bruteforce it!
  81509. try {
  81510. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  81511. }
  81512. catch (e) {
  81513. BABYLON.Tools.Warn(e);
  81514. }
  81515. };
  81516. OimoJSPlugin.prototype.isSupported = function () {
  81517. return this.BJSOIMO !== undefined;
  81518. };
  81519. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  81520. if (!impostor.physicsBody.sleeping) {
  81521. //TODO check that
  81522. /*if (impostor.physicsBody.shapes.next) {
  81523. var parentShape = this._getLastShape(impostor.physicsBody);
  81524. impostor.object.position.copyFrom(parentShape.position);
  81525. console.log(parentShape.position);
  81526. } else {*/
  81527. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  81528. //}
  81529. if (impostor.object.rotationQuaternion) {
  81530. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  81531. }
  81532. }
  81533. };
  81534. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  81535. var body = impostor.physicsBody;
  81536. body.position.copy(newPosition);
  81537. body.orientation.copy(newRotation);
  81538. body.syncShapes();
  81539. body.awake();
  81540. };
  81541. /*private _getLastShape(body: any): any {
  81542. var lastShape = body.shapes;
  81543. while (lastShape.next) {
  81544. lastShape = lastShape.next;
  81545. }
  81546. return lastShape;
  81547. }*/
  81548. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  81549. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  81550. };
  81551. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  81552. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  81553. };
  81554. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  81555. var v = impostor.physicsBody.linearVelocity;
  81556. if (!v) {
  81557. return null;
  81558. }
  81559. return new BABYLON.Vector3(v.x, v.y, v.z);
  81560. };
  81561. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  81562. var v = impostor.physicsBody.angularVelocity;
  81563. if (!v) {
  81564. return null;
  81565. }
  81566. return new BABYLON.Vector3(v.x, v.y, v.z);
  81567. };
  81568. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  81569. var staticBody = mass === 0;
  81570. //this will actually set the body's density and not its mass.
  81571. //But this is how oimo treats the mass variable.
  81572. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  81573. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  81574. };
  81575. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  81576. return impostor.physicsBody.shapes.density;
  81577. };
  81578. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  81579. return impostor.physicsBody.shapes.friction;
  81580. };
  81581. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  81582. impostor.physicsBody.shapes.friction = friction;
  81583. };
  81584. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  81585. return impostor.physicsBody.shapes.restitution;
  81586. };
  81587. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  81588. impostor.physicsBody.shapes.restitution = restitution;
  81589. };
  81590. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  81591. impostor.physicsBody.sleep();
  81592. };
  81593. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  81594. impostor.physicsBody.awake();
  81595. };
  81596. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  81597. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  81598. if (minDistance !== void 0) {
  81599. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  81600. }
  81601. };
  81602. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  81603. //TODO separate rotational and transational motors.
  81604. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  81605. if (motor) {
  81606. motor.setMotor(speed, maxForce);
  81607. }
  81608. };
  81609. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  81610. //TODO separate rotational and transational motors.
  81611. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  81612. if (motor) {
  81613. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  81614. }
  81615. };
  81616. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  81617. var body = impostor.physicsBody;
  81618. mesh.position.x = body.position.x;
  81619. mesh.position.y = body.position.y;
  81620. mesh.position.z = body.position.z;
  81621. if (mesh.rotationQuaternion) {
  81622. mesh.rotationQuaternion.x = body.orientation.x;
  81623. mesh.rotationQuaternion.y = body.orientation.y;
  81624. mesh.rotationQuaternion.z = body.orientation.z;
  81625. mesh.rotationQuaternion.w = body.orientation.s;
  81626. }
  81627. };
  81628. OimoJSPlugin.prototype.getRadius = function (impostor) {
  81629. return impostor.physicsBody.shapes.radius;
  81630. };
  81631. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  81632. var shape = impostor.physicsBody.shapes;
  81633. result.x = shape.halfWidth * 2;
  81634. result.y = shape.halfHeight * 2;
  81635. result.z = shape.halfDepth * 2;
  81636. };
  81637. OimoJSPlugin.prototype.dispose = function () {
  81638. this.world.clear();
  81639. };
  81640. return OimoJSPlugin;
  81641. }());
  81642. BABYLON.OimoJSPlugin = OimoJSPlugin;
  81643. })(BABYLON || (BABYLON = {}));
  81644. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  81645. "use strict";
  81646. var BABYLON;
  81647. (function (BABYLON) {
  81648. /*
  81649. * Based on jsTGALoader - Javascript loader for TGA file
  81650. * By Vincent Thibault
  81651. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  81652. */
  81653. var TGATools = /** @class */ (function () {
  81654. function TGATools() {
  81655. }
  81656. TGATools.GetTGAHeader = function (data) {
  81657. var offset = 0;
  81658. var header = {
  81659. id_length: data[offset++],
  81660. colormap_type: data[offset++],
  81661. image_type: data[offset++],
  81662. colormap_index: data[offset++] | data[offset++] << 8,
  81663. colormap_length: data[offset++] | data[offset++] << 8,
  81664. colormap_size: data[offset++],
  81665. origin: [
  81666. data[offset++] | data[offset++] << 8,
  81667. data[offset++] | data[offset++] << 8
  81668. ],
  81669. width: data[offset++] | data[offset++] << 8,
  81670. height: data[offset++] | data[offset++] << 8,
  81671. pixel_size: data[offset++],
  81672. flags: data[offset++]
  81673. };
  81674. return header;
  81675. };
  81676. TGATools.UploadContent = function (gl, data) {
  81677. // Not enough data to contain header ?
  81678. if (data.length < 19) {
  81679. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  81680. return;
  81681. }
  81682. // Read Header
  81683. var offset = 18;
  81684. var header = TGATools.GetTGAHeader(data);
  81685. // Assume it's a valid Targa file.
  81686. if (header.id_length + offset > data.length) {
  81687. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  81688. return;
  81689. }
  81690. // Skip not needed data
  81691. offset += header.id_length;
  81692. var use_rle = false;
  81693. var use_pal = false;
  81694. var use_grey = false;
  81695. // Get some informations.
  81696. switch (header.image_type) {
  81697. case TGATools._TYPE_RLE_INDEXED:
  81698. use_rle = true;
  81699. case TGATools._TYPE_INDEXED:
  81700. use_pal = true;
  81701. break;
  81702. case TGATools._TYPE_RLE_RGB:
  81703. use_rle = true;
  81704. case TGATools._TYPE_RGB:
  81705. // use_rgb = true;
  81706. break;
  81707. case TGATools._TYPE_RLE_GREY:
  81708. use_rle = true;
  81709. case TGATools._TYPE_GREY:
  81710. use_grey = true;
  81711. break;
  81712. }
  81713. var pixel_data;
  81714. // var numAlphaBits = header.flags & 0xf;
  81715. var pixel_size = header.pixel_size >> 3;
  81716. var pixel_total = header.width * header.height * pixel_size;
  81717. // Read palettes
  81718. var palettes;
  81719. if (use_pal) {
  81720. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  81721. }
  81722. // Read LRE
  81723. if (use_rle) {
  81724. pixel_data = new Uint8Array(pixel_total);
  81725. var c, count, i;
  81726. var localOffset = 0;
  81727. var pixels = new Uint8Array(pixel_size);
  81728. while (offset < pixel_total && localOffset < pixel_total) {
  81729. c = data[offset++];
  81730. count = (c & 0x7f) + 1;
  81731. // RLE pixels
  81732. if (c & 0x80) {
  81733. // Bind pixel tmp array
  81734. for (i = 0; i < pixel_size; ++i) {
  81735. pixels[i] = data[offset++];
  81736. }
  81737. // Copy pixel array
  81738. for (i = 0; i < count; ++i) {
  81739. pixel_data.set(pixels, localOffset + i * pixel_size);
  81740. }
  81741. localOffset += pixel_size * count;
  81742. }
  81743. else {
  81744. count *= pixel_size;
  81745. for (i = 0; i < count; ++i) {
  81746. pixel_data[localOffset + i] = data[offset++];
  81747. }
  81748. localOffset += count;
  81749. }
  81750. }
  81751. }
  81752. else {
  81753. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  81754. }
  81755. // Load to texture
  81756. var x_start, y_start, x_step, y_step, y_end, x_end;
  81757. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  81758. default:
  81759. case TGATools._ORIGIN_UL:
  81760. x_start = 0;
  81761. x_step = 1;
  81762. x_end = header.width;
  81763. y_start = 0;
  81764. y_step = 1;
  81765. y_end = header.height;
  81766. break;
  81767. case TGATools._ORIGIN_BL:
  81768. x_start = 0;
  81769. x_step = 1;
  81770. x_end = header.width;
  81771. y_start = header.height - 1;
  81772. y_step = -1;
  81773. y_end = -1;
  81774. break;
  81775. case TGATools._ORIGIN_UR:
  81776. x_start = header.width - 1;
  81777. x_step = -1;
  81778. x_end = -1;
  81779. y_start = 0;
  81780. y_step = 1;
  81781. y_end = header.height;
  81782. break;
  81783. case TGATools._ORIGIN_BR:
  81784. x_start = header.width - 1;
  81785. x_step = -1;
  81786. x_end = -1;
  81787. y_start = header.height - 1;
  81788. y_step = -1;
  81789. y_end = -1;
  81790. break;
  81791. }
  81792. // Load the specify method
  81793. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  81794. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  81795. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  81796. };
  81797. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  81798. var image = pixel_data, colormap = palettes;
  81799. var width = header.width, height = header.height;
  81800. var color, i = 0, x, y;
  81801. var imageData = new Uint8Array(width * height * 4);
  81802. for (y = y_start; y !== y_end; y += y_step) {
  81803. for (x = x_start; x !== x_end; x += x_step, i++) {
  81804. color = image[i];
  81805. imageData[(x + width * y) * 4 + 3] = 255;
  81806. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  81807. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  81808. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  81809. }
  81810. }
  81811. return imageData;
  81812. };
  81813. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  81814. var image = pixel_data;
  81815. var width = header.width, height = header.height;
  81816. var color, i = 0, x, y;
  81817. var imageData = new Uint8Array(width * height * 4);
  81818. for (y = y_start; y !== y_end; y += y_step) {
  81819. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  81820. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  81821. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  81822. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  81823. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  81824. imageData[(x + width * y) * 4 + 0] = r;
  81825. imageData[(x + width * y) * 4 + 1] = g;
  81826. imageData[(x + width * y) * 4 + 2] = b;
  81827. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  81828. }
  81829. }
  81830. return imageData;
  81831. };
  81832. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  81833. var image = pixel_data;
  81834. var width = header.width, height = header.height;
  81835. var i = 0, x, y;
  81836. var imageData = new Uint8Array(width * height * 4);
  81837. for (y = y_start; y !== y_end; y += y_step) {
  81838. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  81839. imageData[(x + width * y) * 4 + 3] = 255;
  81840. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  81841. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  81842. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  81843. }
  81844. }
  81845. return imageData;
  81846. };
  81847. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  81848. var image = pixel_data;
  81849. var width = header.width, height = header.height;
  81850. var i = 0, x, y;
  81851. var imageData = new Uint8Array(width * height * 4);
  81852. for (y = y_start; y !== y_end; y += y_step) {
  81853. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  81854. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  81855. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  81856. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  81857. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  81858. }
  81859. }
  81860. return imageData;
  81861. };
  81862. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  81863. var image = pixel_data;
  81864. var width = header.width, height = header.height;
  81865. var color, i = 0, x, y;
  81866. var imageData = new Uint8Array(width * height * 4);
  81867. for (y = y_start; y !== y_end; y += y_step) {
  81868. for (x = x_start; x !== x_end; x += x_step, i++) {
  81869. color = image[i];
  81870. imageData[(x + width * y) * 4 + 0] = color;
  81871. imageData[(x + width * y) * 4 + 1] = color;
  81872. imageData[(x + width * y) * 4 + 2] = color;
  81873. imageData[(x + width * y) * 4 + 3] = 255;
  81874. }
  81875. }
  81876. return imageData;
  81877. };
  81878. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  81879. var image = pixel_data;
  81880. var width = header.width, height = header.height;
  81881. var i = 0, x, y;
  81882. var imageData = new Uint8Array(width * height * 4);
  81883. for (y = y_start; y !== y_end; y += y_step) {
  81884. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  81885. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  81886. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  81887. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  81888. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  81889. }
  81890. }
  81891. return imageData;
  81892. };
  81893. //private static _TYPE_NO_DATA = 0;
  81894. TGATools._TYPE_INDEXED = 1;
  81895. TGATools._TYPE_RGB = 2;
  81896. TGATools._TYPE_GREY = 3;
  81897. TGATools._TYPE_RLE_INDEXED = 9;
  81898. TGATools._TYPE_RLE_RGB = 10;
  81899. TGATools._TYPE_RLE_GREY = 11;
  81900. TGATools._ORIGIN_MASK = 0x30;
  81901. TGATools._ORIGIN_SHIFT = 0x04;
  81902. TGATools._ORIGIN_BL = 0x00;
  81903. TGATools._ORIGIN_BR = 0x01;
  81904. TGATools._ORIGIN_UL = 0x02;
  81905. TGATools._ORIGIN_UR = 0x03;
  81906. return TGATools;
  81907. }());
  81908. BABYLON.TGATools = TGATools;
  81909. })(BABYLON || (BABYLON = {}));
  81910. //# sourceMappingURL=babylon.tga.js.map
  81911. "use strict";
  81912. var BABYLON;
  81913. (function (BABYLON) {
  81914. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  81915. // All values and structures referenced from:
  81916. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  81917. var DDS_MAGIC = 0x20534444;
  81918. var
  81919. //DDSD_CAPS = 0x1,
  81920. //DDSD_HEIGHT = 0x2,
  81921. //DDSD_WIDTH = 0x4,
  81922. //DDSD_PITCH = 0x8,
  81923. //DDSD_PIXELFORMAT = 0x1000,
  81924. DDSD_MIPMAPCOUNT = 0x20000;
  81925. //DDSD_LINEARSIZE = 0x80000,
  81926. //DDSD_DEPTH = 0x800000;
  81927. // var DDSCAPS_COMPLEX = 0x8,
  81928. // DDSCAPS_MIPMAP = 0x400000,
  81929. // DDSCAPS_TEXTURE = 0x1000;
  81930. var DDSCAPS2_CUBEMAP = 0x200;
  81931. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  81932. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  81933. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  81934. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  81935. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  81936. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  81937. // DDSCAPS2_VOLUME = 0x200000;
  81938. var
  81939. //DDPF_ALPHAPIXELS = 0x1,
  81940. //DDPF_ALPHA = 0x2,
  81941. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  81942. //DDPF_YUV = 0x200,
  81943. DDPF_LUMINANCE = 0x20000;
  81944. function FourCCToInt32(value) {
  81945. return value.charCodeAt(0) +
  81946. (value.charCodeAt(1) << 8) +
  81947. (value.charCodeAt(2) << 16) +
  81948. (value.charCodeAt(3) << 24);
  81949. }
  81950. function Int32ToFourCC(value) {
  81951. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  81952. }
  81953. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  81954. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  81955. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  81956. var FOURCC_DX10 = FourCCToInt32("DX10");
  81957. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  81958. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  81959. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  81960. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  81961. var headerLengthInt = 31; // The header length in 32 bit ints
  81962. // Offsets into the header array
  81963. var off_magic = 0;
  81964. var off_size = 1;
  81965. var off_flags = 2;
  81966. var off_height = 3;
  81967. var off_width = 4;
  81968. var off_mipmapCount = 7;
  81969. var off_pfFlags = 20;
  81970. var off_pfFourCC = 21;
  81971. var off_RGBbpp = 22;
  81972. var off_RMask = 23;
  81973. var off_GMask = 24;
  81974. var off_BMask = 25;
  81975. var off_AMask = 26;
  81976. // var off_caps1 = 27;
  81977. var off_caps2 = 28;
  81978. // var off_caps3 = 29;
  81979. // var off_caps4 = 30;
  81980. var off_dxgiFormat = 32;
  81981. ;
  81982. var DDSTools = /** @class */ (function () {
  81983. function DDSTools() {
  81984. }
  81985. DDSTools.GetDDSInfo = function (arrayBuffer) {
  81986. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  81987. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  81988. var mipmapCount = 1;
  81989. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  81990. mipmapCount = Math.max(1, header[off_mipmapCount]);
  81991. }
  81992. var fourCC = header[off_pfFourCC];
  81993. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  81994. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  81995. switch (fourCC) {
  81996. case FOURCC_D3DFMT_R16G16B16A16F:
  81997. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  81998. break;
  81999. case FOURCC_D3DFMT_R32G32B32A32F:
  82000. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82001. break;
  82002. case FOURCC_DX10:
  82003. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  82004. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82005. break;
  82006. }
  82007. }
  82008. return {
  82009. width: header[off_width],
  82010. height: header[off_height],
  82011. mipmapCount: mipmapCount,
  82012. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  82013. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  82014. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  82015. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  82016. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  82017. dxgiFormat: dxgiFormat,
  82018. textureType: textureType
  82019. };
  82020. };
  82021. DDSTools._ToHalfFloat = function (value) {
  82022. if (!DDSTools._FloatView) {
  82023. DDSTools._FloatView = new Float32Array(1);
  82024. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  82025. }
  82026. DDSTools._FloatView[0] = value;
  82027. var x = DDSTools._Int32View[0];
  82028. var bits = (x >> 16) & 0x8000; /* Get the sign */
  82029. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  82030. var e = (x >> 23) & 0xff; /* Using int is faster here */
  82031. /* If zero, or denormal, or exponent underflows too much for a denormal
  82032. * half, return signed zero. */
  82033. if (e < 103) {
  82034. return bits;
  82035. }
  82036. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  82037. if (e > 142) {
  82038. bits |= 0x7c00;
  82039. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  82040. * not Inf, so make sure we set one mantissa bit too. */
  82041. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  82042. return bits;
  82043. }
  82044. /* If exponent underflows but not too much, return a denormal */
  82045. if (e < 113) {
  82046. m |= 0x0800;
  82047. /* Extra rounding may overflow and set mantissa to 0 and exponent
  82048. * to 1, which is OK. */
  82049. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  82050. return bits;
  82051. }
  82052. bits |= ((e - 112) << 10) | (m >> 1);
  82053. bits += m & 1;
  82054. return bits;
  82055. };
  82056. DDSTools._FromHalfFloat = function (value) {
  82057. var s = (value & 0x8000) >> 15;
  82058. var e = (value & 0x7C00) >> 10;
  82059. var f = value & 0x03FF;
  82060. if (e === 0) {
  82061. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  82062. }
  82063. else if (e == 0x1F) {
  82064. return f ? NaN : ((s ? -1 : 1) * Infinity);
  82065. }
  82066. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  82067. };
  82068. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  82069. var destArray = new Float32Array(dataLength);
  82070. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  82071. var index = 0;
  82072. for (var y = 0; y < height; y++) {
  82073. for (var x = 0; x < width; x++) {
  82074. var srcPos = (x + y * width) * 4;
  82075. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  82076. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  82077. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  82078. if (DDSTools.StoreLODInAlphaChannel) {
  82079. destArray[index + 3] = lod;
  82080. }
  82081. else {
  82082. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  82083. }
  82084. index += 4;
  82085. }
  82086. }
  82087. return destArray;
  82088. };
  82089. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  82090. if (DDSTools.StoreLODInAlphaChannel) {
  82091. var destArray = new Uint16Array(dataLength);
  82092. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  82093. var index = 0;
  82094. for (var y = 0; y < height; y++) {
  82095. for (var x = 0; x < width; x++) {
  82096. var srcPos = (x + y * width) * 4;
  82097. destArray[index] = srcData[srcPos];
  82098. destArray[index + 1] = srcData[srcPos + 1];
  82099. destArray[index + 2] = srcData[srcPos + 2];
  82100. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  82101. index += 4;
  82102. }
  82103. }
  82104. return destArray;
  82105. }
  82106. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  82107. };
  82108. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  82109. if (DDSTools.StoreLODInAlphaChannel) {
  82110. var destArray = new Float32Array(dataLength);
  82111. var srcData = new Float32Array(arrayBuffer, dataOffset);
  82112. var index = 0;
  82113. for (var y = 0; y < height; y++) {
  82114. for (var x = 0; x < width; x++) {
  82115. var srcPos = (x + y * width) * 4;
  82116. destArray[index] = srcData[srcPos];
  82117. destArray[index + 1] = srcData[srcPos + 1];
  82118. destArray[index + 2] = srcData[srcPos + 2];
  82119. destArray[index + 3] = lod;
  82120. index += 4;
  82121. }
  82122. }
  82123. return destArray;
  82124. }
  82125. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  82126. };
  82127. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  82128. var destArray = new Uint8Array(dataLength);
  82129. var srcData = new Float32Array(arrayBuffer, dataOffset);
  82130. var index = 0;
  82131. for (var y = 0; y < height; y++) {
  82132. for (var x = 0; x < width; x++) {
  82133. var srcPos = (x + y * width) * 4;
  82134. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  82135. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  82136. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  82137. if (DDSTools.StoreLODInAlphaChannel) {
  82138. destArray[index + 3] = lod;
  82139. }
  82140. else {
  82141. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  82142. }
  82143. index += 4;
  82144. }
  82145. }
  82146. return destArray;
  82147. };
  82148. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  82149. var destArray = new Uint8Array(dataLength);
  82150. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  82151. var index = 0;
  82152. for (var y = 0; y < height; y++) {
  82153. for (var x = 0; x < width; x++) {
  82154. var srcPos = (x + y * width) * 4;
  82155. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  82156. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  82157. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  82158. if (DDSTools.StoreLODInAlphaChannel) {
  82159. destArray[index + 3] = lod;
  82160. }
  82161. else {
  82162. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  82163. }
  82164. index += 4;
  82165. }
  82166. }
  82167. return destArray;
  82168. };
  82169. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  82170. var byteArray = new Uint8Array(dataLength);
  82171. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  82172. var index = 0;
  82173. for (var y = 0; y < height; y++) {
  82174. for (var x = 0; x < width; x++) {
  82175. var srcPos = (x + y * width) * 4;
  82176. byteArray[index] = srcData[srcPos + rOffset];
  82177. byteArray[index + 1] = srcData[srcPos + gOffset];
  82178. byteArray[index + 2] = srcData[srcPos + bOffset];
  82179. byteArray[index + 3] = srcData[srcPos + aOffset];
  82180. index += 4;
  82181. }
  82182. }
  82183. return byteArray;
  82184. };
  82185. DDSTools._ExtractLongWordOrder = function (value) {
  82186. if (value === 0 || value === 255 || value === -16777216) {
  82187. return 0;
  82188. }
  82189. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  82190. };
  82191. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  82192. var byteArray = new Uint8Array(dataLength);
  82193. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  82194. var index = 0;
  82195. for (var y = 0; y < height; y++) {
  82196. for (var x = 0; x < width; x++) {
  82197. var srcPos = (x + y * width) * 3;
  82198. byteArray[index] = srcData[srcPos + rOffset];
  82199. byteArray[index + 1] = srcData[srcPos + gOffset];
  82200. byteArray[index + 2] = srcData[srcPos + bOffset];
  82201. index += 3;
  82202. }
  82203. }
  82204. return byteArray;
  82205. };
  82206. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  82207. var byteArray = new Uint8Array(dataLength);
  82208. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  82209. var index = 0;
  82210. for (var y = 0; y < height; y++) {
  82211. for (var x = 0; x < width; x++) {
  82212. var srcPos = (x + y * width);
  82213. byteArray[index] = srcData[srcPos];
  82214. index++;
  82215. }
  82216. }
  82217. return byteArray;
  82218. };
  82219. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  82220. if (lodIndex === void 0) { lodIndex = -1; }
  82221. var ext = engine.getCaps().s3tc;
  82222. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  82223. var fourCC, width, height, dataLength = 0, dataOffset;
  82224. var byteArray, mipmapCount, mip;
  82225. var internalFormat = 0;
  82226. var format = 0;
  82227. var blockBytes = 1;
  82228. if (header[off_magic] !== DDS_MAGIC) {
  82229. BABYLON.Tools.Error("Invalid magic number in DDS header");
  82230. return;
  82231. }
  82232. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  82233. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  82234. return;
  82235. }
  82236. if (info.isCompressed && !ext) {
  82237. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  82238. return;
  82239. }
  82240. var bpp = header[off_RGBbpp];
  82241. dataOffset = header[off_size] + 4;
  82242. var computeFormats = false;
  82243. if (info.isFourCC) {
  82244. fourCC = header[off_pfFourCC];
  82245. switch (fourCC) {
  82246. case FOURCC_DXT1:
  82247. blockBytes = 8;
  82248. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  82249. break;
  82250. case FOURCC_DXT3:
  82251. blockBytes = 16;
  82252. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  82253. break;
  82254. case FOURCC_DXT5:
  82255. blockBytes = 16;
  82256. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  82257. break;
  82258. case FOURCC_D3DFMT_R16G16B16A16F:
  82259. computeFormats = true;
  82260. break;
  82261. case FOURCC_D3DFMT_R32G32B32A32F:
  82262. computeFormats = true;
  82263. break;
  82264. case FOURCC_DX10:
  82265. // There is an additionnal header so dataOffset need to be changed
  82266. dataOffset += 5 * 4; // 5 uints
  82267. var supported = false;
  82268. switch (info.dxgiFormat) {
  82269. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  82270. computeFormats = true;
  82271. supported = true;
  82272. break;
  82273. case DXGI_FORMAT_B8G8R8X8_UNORM:
  82274. info.isRGB = true;
  82275. info.isFourCC = false;
  82276. bpp = 32;
  82277. supported = true;
  82278. break;
  82279. }
  82280. if (supported) {
  82281. break;
  82282. }
  82283. default:
  82284. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  82285. return;
  82286. }
  82287. }
  82288. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  82289. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  82290. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  82291. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  82292. if (computeFormats) {
  82293. format = engine._getWebGLTextureType(info.textureType);
  82294. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  82295. }
  82296. mipmapCount = 1;
  82297. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  82298. mipmapCount = Math.max(1, header[off_mipmapCount]);
  82299. }
  82300. for (var face = 0; face < faces; face++) {
  82301. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  82302. width = header[off_width];
  82303. height = header[off_height];
  82304. for (mip = 0; mip < mipmapCount; ++mip) {
  82305. if (lodIndex === -1 || lodIndex === mip) {
  82306. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  82307. var i = (lodIndex === -1) ? mip : 0;
  82308. if (!info.isCompressed && info.isFourCC) {
  82309. dataLength = width * height * 4;
  82310. var floatArray = null;
  82311. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  82312. if (bpp === 128) {
  82313. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  82314. }
  82315. else if (bpp === 64) {
  82316. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  82317. }
  82318. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  82319. format = engine._getWebGLTextureType(info.textureType);
  82320. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  82321. }
  82322. else {
  82323. if (bpp === 128) {
  82324. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  82325. }
  82326. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  82327. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  82328. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82329. format = engine._getWebGLTextureType(info.textureType);
  82330. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  82331. }
  82332. else {
  82333. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  82334. }
  82335. }
  82336. if (floatArray) {
  82337. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  82338. }
  82339. }
  82340. else if (info.isRGB) {
  82341. if (bpp === 24) {
  82342. dataLength = width * height * 3;
  82343. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  82344. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  82345. }
  82346. else {
  82347. dataLength = width * height * 4;
  82348. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  82349. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  82350. }
  82351. }
  82352. else if (info.isLuminance) {
  82353. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  82354. var unpaddedRowSize = width;
  82355. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  82356. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  82357. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  82358. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  82359. }
  82360. else {
  82361. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  82362. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  82363. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  82364. }
  82365. }
  82366. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  82367. width *= 0.5;
  82368. height *= 0.5;
  82369. width = Math.max(1.0, width);
  82370. height = Math.max(1.0, height);
  82371. }
  82372. if (currentFace !== undefined) {
  82373. // Loading a single face
  82374. break;
  82375. }
  82376. }
  82377. };
  82378. DDSTools.StoreLODInAlphaChannel = false;
  82379. return DDSTools;
  82380. }());
  82381. BABYLON.DDSTools = DDSTools;
  82382. })(BABYLON || (BABYLON = {}));
  82383. //# sourceMappingURL=babylon.dds.js.map
  82384. "use strict";
  82385. var BABYLON;
  82386. (function (BABYLON) {
  82387. /**
  82388. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  82389. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  82390. */
  82391. var KhronosTextureContainer = /** @class */ (function () {
  82392. /**
  82393. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  82394. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  82395. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  82396. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  82397. */
  82398. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  82399. this.arrayBuffer = arrayBuffer;
  82400. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  82401. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  82402. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  82403. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  82404. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  82405. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  82406. BABYLON.Tools.Error("texture missing KTX identifier");
  82407. return;
  82408. }
  82409. // load the reset of the header in native 32 bit int
  82410. var header = new Int32Array(this.arrayBuffer, 12, 13);
  82411. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  82412. var oppositeEndianess = header[0] === 0x01020304;
  82413. // read all the header elements in order they exist in the file, without modification (sans endainness)
  82414. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  82415. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  82416. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  82417. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  82418. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  82419. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  82420. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  82421. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  82422. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  82423. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  82424. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  82425. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  82426. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  82427. if (this.glType !== 0) {
  82428. BABYLON.Tools.Error("only compressed formats currently supported");
  82429. return;
  82430. }
  82431. else {
  82432. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  82433. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  82434. }
  82435. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  82436. BABYLON.Tools.Error("only 2D textures currently supported");
  82437. return;
  82438. }
  82439. if (this.numberOfArrayElements !== 0) {
  82440. BABYLON.Tools.Error("texture arrays not currently supported");
  82441. return;
  82442. }
  82443. if (this.numberOfFaces !== facesExpected) {
  82444. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  82445. return;
  82446. }
  82447. // we now have a completely validated file, so could use existence of loadType as success
  82448. // would need to make this more elaborate & adjust checks above to support more than one load type
  82449. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  82450. }
  82451. // not as fast hardware based, but will probably never need to use
  82452. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  82453. return ((val & 0xFF) << 24)
  82454. | ((val & 0xFF00) << 8)
  82455. | ((val >> 8) & 0xFF00)
  82456. | ((val >> 24) & 0xFF);
  82457. };
  82458. /**
  82459. * It is assumed that the texture has already been created & is currently bound
  82460. */
  82461. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  82462. switch (this.loadType) {
  82463. case KhronosTextureContainer.COMPRESSED_2D:
  82464. this._upload2DCompressedLevels(gl, loadMipmaps);
  82465. break;
  82466. case KhronosTextureContainer.TEX_2D:
  82467. case KhronosTextureContainer.COMPRESSED_3D:
  82468. case KhronosTextureContainer.TEX_3D:
  82469. }
  82470. };
  82471. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  82472. // initialize width & height for level 1
  82473. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  82474. var width = this.pixelWidth;
  82475. var height = this.pixelHeight;
  82476. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  82477. for (var level = 0; level < mipmapCount; level++) {
  82478. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  82479. for (var face = 0; face < this.numberOfFaces; face++) {
  82480. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  82481. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  82482. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  82483. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  82484. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  82485. }
  82486. width = Math.max(1.0, width * 0.5);
  82487. height = Math.max(1.0, height * 0.5);
  82488. }
  82489. };
  82490. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  82491. // load types
  82492. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  82493. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  82494. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  82495. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  82496. return KhronosTextureContainer;
  82497. }());
  82498. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  82499. })(BABYLON || (BABYLON = {}));
  82500. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  82501. "use strict";
  82502. var BABYLON;
  82503. (function (BABYLON) {
  82504. var Debug;
  82505. (function (Debug) {
  82506. /**
  82507. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  82508. */
  82509. var SkeletonViewer = /** @class */ (function () {
  82510. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  82511. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  82512. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  82513. this.skeleton = skeleton;
  82514. this.mesh = mesh;
  82515. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  82516. this.renderingGroupId = renderingGroupId;
  82517. this.color = BABYLON.Color3.White();
  82518. this._debugLines = new Array();
  82519. this._isEnabled = false;
  82520. this._scene = scene;
  82521. this.update();
  82522. this._renderFunction = this.update.bind(this);
  82523. }
  82524. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  82525. get: function () {
  82526. return this._isEnabled;
  82527. },
  82528. set: function (value) {
  82529. if (this._isEnabled === value) {
  82530. return;
  82531. }
  82532. this._isEnabled = value;
  82533. if (value) {
  82534. this._scene.registerBeforeRender(this._renderFunction);
  82535. }
  82536. else {
  82537. this._scene.unregisterBeforeRender(this._renderFunction);
  82538. }
  82539. },
  82540. enumerable: true,
  82541. configurable: true
  82542. });
  82543. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  82544. if (x === void 0) { x = 0; }
  82545. if (y === void 0) { y = 0; }
  82546. if (z === void 0) { z = 0; }
  82547. var tmat = BABYLON.Tmp.Matrix[0];
  82548. var parentBone = bone.getParent();
  82549. tmat.copyFrom(bone.getLocalMatrix());
  82550. if (x !== 0 || y !== 0 || z !== 0) {
  82551. var tmat2 = BABYLON.Tmp.Matrix[1];
  82552. BABYLON.Matrix.IdentityToRef(tmat2);
  82553. tmat2.m[12] = x;
  82554. tmat2.m[13] = y;
  82555. tmat2.m[14] = z;
  82556. tmat2.multiplyToRef(tmat, tmat);
  82557. }
  82558. if (parentBone) {
  82559. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  82560. }
  82561. tmat.multiplyToRef(meshMat, tmat);
  82562. position.x = tmat.m[12];
  82563. position.y = tmat.m[13];
  82564. position.z = tmat.m[14];
  82565. };
  82566. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  82567. var len = bones.length;
  82568. var meshPos = this.mesh.position;
  82569. for (var i = 0; i < len; i++) {
  82570. var bone = bones[i];
  82571. var points = this._debugLines[i];
  82572. if (!points) {
  82573. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82574. this._debugLines[i] = points;
  82575. }
  82576. this._getBonePosition(points[0], bone, meshMat);
  82577. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  82578. points[0].subtractInPlace(meshPos);
  82579. points[1].subtractInPlace(meshPos);
  82580. }
  82581. };
  82582. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  82583. var len = bones.length;
  82584. var boneNum = 0;
  82585. var meshPos = this.mesh.position;
  82586. for (var i = len - 1; i >= 0; i--) {
  82587. var childBone = bones[i];
  82588. var parentBone = childBone.getParent();
  82589. if (!parentBone) {
  82590. continue;
  82591. }
  82592. var points = this._debugLines[boneNum];
  82593. if (!points) {
  82594. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82595. this._debugLines[boneNum] = points;
  82596. }
  82597. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  82598. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  82599. points[0].subtractInPlace(meshPos);
  82600. points[1].subtractInPlace(meshPos);
  82601. boneNum++;
  82602. }
  82603. };
  82604. SkeletonViewer.prototype.update = function () {
  82605. if (this.autoUpdateBonesMatrices) {
  82606. this.skeleton.computeAbsoluteTransforms();
  82607. }
  82608. if (this.skeleton.bones[0].length === undefined) {
  82609. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  82610. }
  82611. else {
  82612. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  82613. }
  82614. if (!this._debugMesh) {
  82615. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  82616. this._debugMesh.renderingGroupId = this.renderingGroupId;
  82617. }
  82618. else {
  82619. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  82620. }
  82621. this._debugMesh.position.copyFrom(this.mesh.position);
  82622. this._debugMesh.color = this.color;
  82623. };
  82624. SkeletonViewer.prototype.dispose = function () {
  82625. if (this._debugMesh) {
  82626. this.isEnabled = false;
  82627. this._debugMesh.dispose();
  82628. this._debugMesh = null;
  82629. }
  82630. };
  82631. return SkeletonViewer;
  82632. }());
  82633. Debug.SkeletonViewer = SkeletonViewer;
  82634. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  82635. })(BABYLON || (BABYLON = {}));
  82636. //# sourceMappingURL=babylon.skeletonViewer.js.map
  82637. "use strict";
  82638. /**
  82639. * Module Debug contains the (visual) components to debug a scene correctly
  82640. */
  82641. var BABYLON;
  82642. (function (BABYLON) {
  82643. var Debug;
  82644. (function (Debug) {
  82645. /**
  82646. * The Axes viewer will show 3 axes in a specific point in space
  82647. */
  82648. var AxesViewer = /** @class */ (function () {
  82649. function AxesViewer(scene, scaleLines) {
  82650. if (scaleLines === void 0) { scaleLines = 1; }
  82651. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82652. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82653. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82654. this.scaleLines = 1;
  82655. this.scaleLines = scaleLines;
  82656. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  82657. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  82658. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  82659. this._xmesh.renderingGroupId = 2;
  82660. this._ymesh.renderingGroupId = 2;
  82661. this._zmesh.renderingGroupId = 2;
  82662. this._xmesh.material.checkReadyOnlyOnce = true;
  82663. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  82664. this._ymesh.material.checkReadyOnlyOnce = true;
  82665. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  82666. this._zmesh.material.checkReadyOnlyOnce = true;
  82667. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  82668. this.scene = scene;
  82669. }
  82670. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  82671. var scaleLines = this.scaleLines;
  82672. if (this._xmesh) {
  82673. this._xmesh.position.copyFrom(position);
  82674. }
  82675. if (this._ymesh) {
  82676. this._ymesh.position.copyFrom(position);
  82677. }
  82678. if (this._zmesh) {
  82679. this._zmesh.position.copyFrom(position);
  82680. }
  82681. var point2 = this._xline[1];
  82682. point2.x = xaxis.x * scaleLines;
  82683. point2.y = xaxis.y * scaleLines;
  82684. point2.z = xaxis.z * scaleLines;
  82685. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  82686. point2 = this._yline[1];
  82687. point2.x = yaxis.x * scaleLines;
  82688. point2.y = yaxis.y * scaleLines;
  82689. point2.z = yaxis.z * scaleLines;
  82690. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  82691. point2 = this._zline[1];
  82692. point2.x = zaxis.x * scaleLines;
  82693. point2.y = zaxis.y * scaleLines;
  82694. point2.z = zaxis.z * scaleLines;
  82695. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  82696. };
  82697. AxesViewer.prototype.dispose = function () {
  82698. if (this._xmesh) {
  82699. this._xmesh.dispose();
  82700. }
  82701. if (this._ymesh) {
  82702. this._ymesh.dispose();
  82703. }
  82704. if (this._zmesh) {
  82705. this._zmesh.dispose();
  82706. }
  82707. this._xmesh = null;
  82708. this._ymesh = null;
  82709. this._zmesh = null;
  82710. this.scene = null;
  82711. };
  82712. return AxesViewer;
  82713. }());
  82714. Debug.AxesViewer = AxesViewer;
  82715. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  82716. })(BABYLON || (BABYLON = {}));
  82717. //# sourceMappingURL=babylon.axesViewer.js.map
  82718. "use strict";
  82719. var BABYLON;
  82720. (function (BABYLON) {
  82721. var Debug;
  82722. (function (Debug) {
  82723. /**
  82724. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  82725. */
  82726. var BoneAxesViewer = /** @class */ (function (_super) {
  82727. __extends(BoneAxesViewer, _super);
  82728. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  82729. if (scaleLines === void 0) { scaleLines = 1; }
  82730. var _this = _super.call(this, scene, scaleLines) || this;
  82731. _this.pos = BABYLON.Vector3.Zero();
  82732. _this.xaxis = BABYLON.Vector3.Zero();
  82733. _this.yaxis = BABYLON.Vector3.Zero();
  82734. _this.zaxis = BABYLON.Vector3.Zero();
  82735. _this.mesh = mesh;
  82736. _this.bone = bone;
  82737. return _this;
  82738. }
  82739. BoneAxesViewer.prototype.update = function () {
  82740. if (!this.mesh || !this.bone) {
  82741. return;
  82742. }
  82743. var bone = this.bone;
  82744. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  82745. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  82746. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  82747. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  82748. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  82749. };
  82750. BoneAxesViewer.prototype.dispose = function () {
  82751. if (this.mesh) {
  82752. this.mesh = null;
  82753. this.bone = null;
  82754. _super.prototype.dispose.call(this);
  82755. }
  82756. };
  82757. return BoneAxesViewer;
  82758. }(Debug.AxesViewer));
  82759. Debug.BoneAxesViewer = BoneAxesViewer;
  82760. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  82761. })(BABYLON || (BABYLON = {}));
  82762. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  82763. "use strict";
  82764. var BABYLON;
  82765. (function (BABYLON) {
  82766. var RayHelper = /** @class */ (function () {
  82767. function RayHelper(ray) {
  82768. this.ray = ray;
  82769. }
  82770. RayHelper.CreateAndShow = function (ray, scene, color) {
  82771. var helper = new RayHelper(ray);
  82772. helper.show(scene, color);
  82773. return helper;
  82774. };
  82775. RayHelper.prototype.show = function (scene, color) {
  82776. if (!this._renderFunction && this.ray) {
  82777. var ray = this.ray;
  82778. this._renderFunction = this._render.bind(this);
  82779. this._scene = scene;
  82780. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  82781. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  82782. if (this._renderFunction) {
  82783. this._scene.registerBeforeRender(this._renderFunction);
  82784. }
  82785. }
  82786. if (color && this._renderLine) {
  82787. this._renderLine.color.copyFrom(color);
  82788. }
  82789. };
  82790. RayHelper.prototype.hide = function () {
  82791. if (this._renderFunction && this._scene) {
  82792. this._scene.unregisterBeforeRender(this._renderFunction);
  82793. this._scene = null;
  82794. this._renderFunction = null;
  82795. if (this._renderLine) {
  82796. this._renderLine.dispose();
  82797. this._renderLine = null;
  82798. }
  82799. this._renderPoints = [];
  82800. }
  82801. };
  82802. RayHelper.prototype._render = function () {
  82803. var ray = this.ray;
  82804. if (!ray) {
  82805. return;
  82806. }
  82807. var point = this._renderPoints[1];
  82808. var len = Math.min(ray.length, 1000000);
  82809. point.copyFrom(ray.direction);
  82810. point.scaleInPlace(len);
  82811. point.addInPlace(ray.origin);
  82812. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  82813. };
  82814. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  82815. this._attachedToMesh = mesh;
  82816. var ray = this.ray;
  82817. if (!ray) {
  82818. return;
  82819. }
  82820. if (!ray.direction) {
  82821. ray.direction = BABYLON.Vector3.Zero();
  82822. }
  82823. if (!ray.origin) {
  82824. ray.origin = BABYLON.Vector3.Zero();
  82825. }
  82826. if (length) {
  82827. ray.length = length;
  82828. }
  82829. if (!meshSpaceOrigin) {
  82830. meshSpaceOrigin = BABYLON.Vector3.Zero();
  82831. }
  82832. if (!meshSpaceDirection) {
  82833. // -1 so that this will work with Mesh.lookAt
  82834. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  82835. }
  82836. if (!this._meshSpaceDirection) {
  82837. this._meshSpaceDirection = meshSpaceDirection.clone();
  82838. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  82839. }
  82840. else {
  82841. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  82842. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  82843. }
  82844. if (!this._updateToMeshFunction) {
  82845. this._updateToMeshFunction = this._updateToMesh.bind(this);
  82846. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  82847. }
  82848. this._updateToMesh();
  82849. };
  82850. RayHelper.prototype.detachFromMesh = function () {
  82851. if (this._attachedToMesh) {
  82852. if (this._updateToMeshFunction) {
  82853. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  82854. }
  82855. this._attachedToMesh = null;
  82856. this._updateToMeshFunction = null;
  82857. }
  82858. };
  82859. RayHelper.prototype._updateToMesh = function () {
  82860. var ray = this.ray;
  82861. if (!this._attachedToMesh || !ray) {
  82862. return;
  82863. }
  82864. if (this._attachedToMesh._isDisposed) {
  82865. this.detachFromMesh();
  82866. return;
  82867. }
  82868. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  82869. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  82870. };
  82871. RayHelper.prototype.dispose = function () {
  82872. this.hide();
  82873. this.detachFromMesh();
  82874. this.ray = null;
  82875. };
  82876. return RayHelper;
  82877. }());
  82878. BABYLON.RayHelper = RayHelper;
  82879. })(BABYLON || (BABYLON = {}));
  82880. //# sourceMappingURL=babylon.rayHelper.js.map
  82881. "use strict";
  82882. var BABYLON;
  82883. (function (BABYLON) {
  82884. // load the inspector using require, if not present in the global namespace.
  82885. var DebugLayer = /** @class */ (function () {
  82886. function DebugLayer(scene) {
  82887. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  82888. this._scene = scene;
  82889. // load inspector using require, if it doesn't exist on the global namespace.
  82890. }
  82891. /** Creates the inspector window. */
  82892. DebugLayer.prototype._createInspector = function (config) {
  82893. if (config === void 0) { config = {}; }
  82894. var popup = config.popup || false;
  82895. var initialTab = config.initialTab || 0;
  82896. var parentElement = config.parentElement || null;
  82897. if (!this._inspector) {
  82898. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  82899. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  82900. } // else nothing to do,; instance is already existing
  82901. };
  82902. DebugLayer.prototype.isVisible = function () {
  82903. if (!this._inspector) {
  82904. return false;
  82905. }
  82906. return true;
  82907. };
  82908. DebugLayer.prototype.hide = function () {
  82909. if (this._inspector) {
  82910. try {
  82911. this._inspector.dispose();
  82912. }
  82913. catch (e) {
  82914. // If the inspector has been removed directly from the inspector tool
  82915. }
  82916. this._inspector = null;
  82917. }
  82918. };
  82919. DebugLayer.prototype.show = function (config) {
  82920. if (config === void 0) { config = {}; }
  82921. if (typeof this.BJSINSPECTOR == 'undefined') {
  82922. // Load inspector and add it to the DOM
  82923. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  82924. }
  82925. else {
  82926. // Otherwise creates the inspector
  82927. this._createInspector(config);
  82928. }
  82929. };
  82930. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  82931. return DebugLayer;
  82932. }());
  82933. BABYLON.DebugLayer = DebugLayer;
  82934. })(BABYLON || (BABYLON = {}));
  82935. //# sourceMappingURL=babylon.debugLayer.js.map
  82936. "use strict";
  82937. var BABYLON;
  82938. (function (BABYLON) {
  82939. var Debug;
  82940. (function (Debug) {
  82941. /**
  82942. * Used to show the physics impostor around the specific mesh.
  82943. */
  82944. var PhysicsViewer = /** @class */ (function () {
  82945. function PhysicsViewer(scene) {
  82946. this._impostors = [];
  82947. this._meshes = [];
  82948. this._numMeshes = 0;
  82949. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  82950. var physicEngine = this._scene.getPhysicsEngine();
  82951. if (physicEngine) {
  82952. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  82953. }
  82954. }
  82955. PhysicsViewer.prototype._updateDebugMeshes = function () {
  82956. var plugin = this._physicsEnginePlugin;
  82957. for (var i = 0; i < this._numMeshes; i++) {
  82958. var impostor = this._impostors[i];
  82959. if (!impostor) {
  82960. continue;
  82961. }
  82962. if (impostor.isDisposed) {
  82963. this.hideImpostor(this._impostors[i--]);
  82964. }
  82965. else {
  82966. var mesh = this._meshes[i];
  82967. if (mesh && plugin) {
  82968. plugin.syncMeshWithImpostor(mesh, impostor);
  82969. }
  82970. }
  82971. }
  82972. };
  82973. PhysicsViewer.prototype.showImpostor = function (impostor) {
  82974. if (!this._scene) {
  82975. return;
  82976. }
  82977. for (var i = 0; i < this._numMeshes; i++) {
  82978. if (this._impostors[i] == impostor) {
  82979. return;
  82980. }
  82981. }
  82982. var debugMesh = this._getDebugMesh(impostor, this._scene);
  82983. if (debugMesh) {
  82984. this._impostors[this._numMeshes] = impostor;
  82985. this._meshes[this._numMeshes] = debugMesh;
  82986. if (this._numMeshes === 0) {
  82987. this._renderFunction = this._updateDebugMeshes.bind(this);
  82988. this._scene.registerBeforeRender(this._renderFunction);
  82989. }
  82990. this._numMeshes++;
  82991. }
  82992. };
  82993. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  82994. if (!impostor || !this._scene) {
  82995. return;
  82996. }
  82997. var removed = false;
  82998. for (var i = 0; i < this._numMeshes; i++) {
  82999. if (this._impostors[i] == impostor) {
  83000. var mesh = this._meshes[i];
  83001. if (!mesh) {
  83002. continue;
  83003. }
  83004. this._scene.removeMesh(mesh);
  83005. mesh.dispose();
  83006. this._numMeshes--;
  83007. if (this._numMeshes > 0) {
  83008. this._meshes[i] = this._meshes[this._numMeshes];
  83009. this._impostors[i] = this._impostors[this._numMeshes];
  83010. this._meshes[this._numMeshes] = null;
  83011. this._impostors[this._numMeshes] = null;
  83012. }
  83013. else {
  83014. this._meshes[0] = null;
  83015. this._impostors[0] = null;
  83016. }
  83017. removed = true;
  83018. break;
  83019. }
  83020. }
  83021. if (removed && this._numMeshes === 0) {
  83022. this._scene.unregisterBeforeRender(this._renderFunction);
  83023. }
  83024. };
  83025. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  83026. if (!this._debugMaterial) {
  83027. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  83028. this._debugMaterial.wireframe = true;
  83029. }
  83030. return this._debugMaterial;
  83031. };
  83032. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  83033. if (!this._debugBoxMesh) {
  83034. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  83035. this._debugBoxMesh.renderingGroupId = 1;
  83036. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  83037. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  83038. scene.removeMesh(this._debugBoxMesh);
  83039. }
  83040. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  83041. };
  83042. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  83043. if (!this._debugSphereMesh) {
  83044. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  83045. this._debugSphereMesh.renderingGroupId = 1;
  83046. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  83047. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  83048. scene.removeMesh(this._debugSphereMesh);
  83049. }
  83050. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  83051. };
  83052. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  83053. var mesh = null;
  83054. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  83055. mesh = this._getDebugBoxMesh(scene);
  83056. impostor.getBoxSizeToRef(mesh.scaling);
  83057. }
  83058. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  83059. mesh = this._getDebugSphereMesh(scene);
  83060. var radius = impostor.getRadius();
  83061. mesh.scaling.x = radius * 2;
  83062. mesh.scaling.y = radius * 2;
  83063. mesh.scaling.z = radius * 2;
  83064. }
  83065. return mesh;
  83066. };
  83067. PhysicsViewer.prototype.dispose = function () {
  83068. for (var i = 0; i < this._numMeshes; i++) {
  83069. this.hideImpostor(this._impostors[i]);
  83070. }
  83071. if (this._debugBoxMesh) {
  83072. this._debugBoxMesh.dispose();
  83073. }
  83074. if (this._debugSphereMesh) {
  83075. this._debugSphereMesh.dispose();
  83076. }
  83077. if (this._debugMaterial) {
  83078. this._debugMaterial.dispose();
  83079. }
  83080. this._impostors.length = 0;
  83081. this._scene = null;
  83082. this._physicsEnginePlugin = null;
  83083. };
  83084. return PhysicsViewer;
  83085. }());
  83086. Debug.PhysicsViewer = PhysicsViewer;
  83087. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  83088. })(BABYLON || (BABYLON = {}));
  83089. //# sourceMappingURL=babylon.physicsViewer.js.map
  83090. "use strict";
  83091. var BABYLON;
  83092. (function (BABYLON) {
  83093. var BoundingBoxRenderer = /** @class */ (function () {
  83094. function BoundingBoxRenderer(scene) {
  83095. this.frontColor = new BABYLON.Color3(1, 1, 1);
  83096. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  83097. this.showBackLines = true;
  83098. this.renderList = new BABYLON.SmartArray(32);
  83099. this._vertexBuffers = {};
  83100. this._scene = scene;
  83101. }
  83102. BoundingBoxRenderer.prototype._prepareRessources = function () {
  83103. if (this._colorShader) {
  83104. return;
  83105. }
  83106. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  83107. attributes: [BABYLON.VertexBuffer.PositionKind],
  83108. uniforms: ["world", "viewProjection", "color"]
  83109. });
  83110. var engine = this._scene.getEngine();
  83111. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  83112. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  83113. this._createIndexBuffer();
  83114. };
  83115. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  83116. var engine = this._scene.getEngine();
  83117. 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]);
  83118. };
  83119. BoundingBoxRenderer.prototype._rebuild = function () {
  83120. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  83121. if (vb) {
  83122. vb._rebuild();
  83123. }
  83124. this._createIndexBuffer();
  83125. };
  83126. BoundingBoxRenderer.prototype.reset = function () {
  83127. this.renderList.reset();
  83128. };
  83129. BoundingBoxRenderer.prototype.render = function () {
  83130. if (this.renderList.length === 0) {
  83131. return;
  83132. }
  83133. this._prepareRessources();
  83134. if (!this._colorShader.isReady()) {
  83135. return;
  83136. }
  83137. var engine = this._scene.getEngine();
  83138. engine.setDepthWrite(false);
  83139. this._colorShader._preBind();
  83140. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  83141. var boundingBox = this.renderList.data[boundingBoxIndex];
  83142. var min = boundingBox.minimum;
  83143. var max = boundingBox.maximum;
  83144. var diff = max.subtract(min);
  83145. var median = min.add(diff.scale(0.5));
  83146. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  83147. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  83148. .multiply(boundingBox.getWorldMatrix());
  83149. // VBOs
  83150. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  83151. if (this.showBackLines) {
  83152. // Back
  83153. engine.setDepthFunctionToGreaterOrEqual();
  83154. this._scene.resetCachedMaterial();
  83155. this._colorShader.setColor4("color", this.backColor.toColor4());
  83156. this._colorShader.bind(worldMatrix);
  83157. // Draw order
  83158. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  83159. }
  83160. // Front
  83161. engine.setDepthFunctionToLess();
  83162. this._scene.resetCachedMaterial();
  83163. this._colorShader.setColor4("color", this.frontColor.toColor4());
  83164. this._colorShader.bind(worldMatrix);
  83165. // Draw order
  83166. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  83167. }
  83168. this._colorShader.unbind();
  83169. engine.setDepthFunctionToLessOrEqual();
  83170. engine.setDepthWrite(true);
  83171. };
  83172. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  83173. this._prepareRessources();
  83174. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  83175. return;
  83176. }
  83177. var engine = this._scene.getEngine();
  83178. engine.setDepthWrite(false);
  83179. engine.setColorWrite(false);
  83180. this._colorShader._preBind();
  83181. var boundingBox = mesh._boundingInfo.boundingBox;
  83182. var min = boundingBox.minimum;
  83183. var max = boundingBox.maximum;
  83184. var diff = max.subtract(min);
  83185. var median = min.add(diff.scale(0.5));
  83186. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  83187. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  83188. .multiply(boundingBox.getWorldMatrix());
  83189. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  83190. engine.setDepthFunctionToLess();
  83191. this._scene.resetCachedMaterial();
  83192. this._colorShader.bind(worldMatrix);
  83193. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  83194. this._colorShader.unbind();
  83195. engine.setDepthFunctionToLessOrEqual();
  83196. engine.setDepthWrite(true);
  83197. engine.setColorWrite(true);
  83198. };
  83199. BoundingBoxRenderer.prototype.dispose = function () {
  83200. if (!this._colorShader) {
  83201. return;
  83202. }
  83203. this.renderList.dispose();
  83204. this._colorShader.dispose();
  83205. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  83206. if (buffer) {
  83207. buffer.dispose();
  83208. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  83209. }
  83210. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  83211. };
  83212. return BoundingBoxRenderer;
  83213. }());
  83214. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  83215. })(BABYLON || (BABYLON = {}));
  83216. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  83217. "use strict";
  83218. var BABYLON;
  83219. (function (BABYLON) {
  83220. var MorphTarget = /** @class */ (function () {
  83221. function MorphTarget(name, influence) {
  83222. if (influence === void 0) { influence = 0; }
  83223. this.name = name;
  83224. this.animations = new Array();
  83225. this._positions = null;
  83226. this._normals = null;
  83227. this._tangents = null;
  83228. this.onInfluenceChanged = new BABYLON.Observable();
  83229. this.influence = influence;
  83230. }
  83231. Object.defineProperty(MorphTarget.prototype, "influence", {
  83232. get: function () {
  83233. return this._influence;
  83234. },
  83235. set: function (influence) {
  83236. if (this._influence === influence) {
  83237. return;
  83238. }
  83239. var previous = this._influence;
  83240. this._influence = influence;
  83241. if (this.onInfluenceChanged.hasObservers) {
  83242. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  83243. }
  83244. },
  83245. enumerable: true,
  83246. configurable: true
  83247. });
  83248. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  83249. get: function () {
  83250. return !!this._positions;
  83251. },
  83252. enumerable: true,
  83253. configurable: true
  83254. });
  83255. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  83256. get: function () {
  83257. return !!this._normals;
  83258. },
  83259. enumerable: true,
  83260. configurable: true
  83261. });
  83262. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  83263. get: function () {
  83264. return !!this._tangents;
  83265. },
  83266. enumerable: true,
  83267. configurable: true
  83268. });
  83269. MorphTarget.prototype.setPositions = function (data) {
  83270. this._positions = data;
  83271. };
  83272. MorphTarget.prototype.getPositions = function () {
  83273. return this._positions;
  83274. };
  83275. MorphTarget.prototype.setNormals = function (data) {
  83276. this._normals = data;
  83277. };
  83278. MorphTarget.prototype.getNormals = function () {
  83279. return this._normals;
  83280. };
  83281. MorphTarget.prototype.setTangents = function (data) {
  83282. this._tangents = data;
  83283. };
  83284. MorphTarget.prototype.getTangents = function () {
  83285. return this._tangents;
  83286. };
  83287. /**
  83288. * Serializes the current target into a Serialization object.
  83289. * Returns the serialized object.
  83290. */
  83291. MorphTarget.prototype.serialize = function () {
  83292. var serializationObject = {};
  83293. serializationObject.name = this.name;
  83294. serializationObject.influence = this.influence;
  83295. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  83296. if (this.hasNormals) {
  83297. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  83298. }
  83299. if (this.hasTangents) {
  83300. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  83301. }
  83302. // Animations
  83303. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  83304. return serializationObject;
  83305. };
  83306. // Statics
  83307. MorphTarget.Parse = function (serializationObject) {
  83308. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  83309. result.setPositions(serializationObject.positions);
  83310. if (serializationObject.normals) {
  83311. result.setNormals(serializationObject.normals);
  83312. }
  83313. if (serializationObject.tangents) {
  83314. result.setTangents(serializationObject.tangents);
  83315. }
  83316. // Animations
  83317. if (serializationObject.animations) {
  83318. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  83319. var parsedAnimation = serializationObject.animations[animationIndex];
  83320. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  83321. }
  83322. }
  83323. return result;
  83324. };
  83325. MorphTarget.FromMesh = function (mesh, name, influence) {
  83326. if (!name) {
  83327. name = mesh.name;
  83328. }
  83329. var result = new MorphTarget(name, influence);
  83330. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  83331. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  83332. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  83333. }
  83334. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  83335. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  83336. }
  83337. return result;
  83338. };
  83339. return MorphTarget;
  83340. }());
  83341. BABYLON.MorphTarget = MorphTarget;
  83342. })(BABYLON || (BABYLON = {}));
  83343. //# sourceMappingURL=babylon.morphTarget.js.map
  83344. "use strict";
  83345. var BABYLON;
  83346. (function (BABYLON) {
  83347. var MorphTargetManager = /** @class */ (function () {
  83348. function MorphTargetManager(scene) {
  83349. if (scene === void 0) { scene = null; }
  83350. this._targets = new Array();
  83351. this._targetObservable = new Array();
  83352. this._activeTargets = new BABYLON.SmartArray(16);
  83353. this._supportsNormals = false;
  83354. this._supportsTangents = false;
  83355. this._vertexCount = 0;
  83356. this._uniqueId = 0;
  83357. this._tempInfluences = new Array();
  83358. if (!scene) {
  83359. scene = BABYLON.Engine.LastCreatedScene;
  83360. }
  83361. this._scene = scene;
  83362. if (this._scene) {
  83363. this._scene.morphTargetManagers.push(this);
  83364. this._uniqueId = this._scene.getUniqueId();
  83365. }
  83366. }
  83367. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  83368. get: function () {
  83369. return this._uniqueId;
  83370. },
  83371. enumerable: true,
  83372. configurable: true
  83373. });
  83374. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  83375. get: function () {
  83376. return this._vertexCount;
  83377. },
  83378. enumerable: true,
  83379. configurable: true
  83380. });
  83381. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  83382. get: function () {
  83383. return this._supportsNormals;
  83384. },
  83385. enumerable: true,
  83386. configurable: true
  83387. });
  83388. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  83389. get: function () {
  83390. return this._supportsTangents;
  83391. },
  83392. enumerable: true,
  83393. configurable: true
  83394. });
  83395. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  83396. get: function () {
  83397. return this._targets.length;
  83398. },
  83399. enumerable: true,
  83400. configurable: true
  83401. });
  83402. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  83403. get: function () {
  83404. return this._activeTargets.length;
  83405. },
  83406. enumerable: true,
  83407. configurable: true
  83408. });
  83409. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  83410. get: function () {
  83411. return this._influences;
  83412. },
  83413. enumerable: true,
  83414. configurable: true
  83415. });
  83416. MorphTargetManager.prototype.getActiveTarget = function (index) {
  83417. return this._activeTargets.data[index];
  83418. };
  83419. MorphTargetManager.prototype.getTarget = function (index) {
  83420. return this._targets[index];
  83421. };
  83422. MorphTargetManager.prototype.addTarget = function (target) {
  83423. var _this = this;
  83424. this._targets.push(target);
  83425. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  83426. _this._syncActiveTargets(needUpdate);
  83427. }));
  83428. this._syncActiveTargets(true);
  83429. };
  83430. MorphTargetManager.prototype.removeTarget = function (target) {
  83431. var index = this._targets.indexOf(target);
  83432. if (index >= 0) {
  83433. this._targets.splice(index, 1);
  83434. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  83435. this._syncActiveTargets(true);
  83436. }
  83437. };
  83438. /**
  83439. * Serializes the current manager into a Serialization object.
  83440. * Returns the serialized object.
  83441. */
  83442. MorphTargetManager.prototype.serialize = function () {
  83443. var serializationObject = {};
  83444. serializationObject.id = this.uniqueId;
  83445. serializationObject.targets = [];
  83446. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  83447. var target = _a[_i];
  83448. serializationObject.targets.push(target.serialize());
  83449. }
  83450. return serializationObject;
  83451. };
  83452. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  83453. var influenceCount = 0;
  83454. this._activeTargets.reset();
  83455. this._supportsNormals = true;
  83456. this._supportsTangents = true;
  83457. this._vertexCount = 0;
  83458. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  83459. var target = _a[_i];
  83460. this._activeTargets.push(target);
  83461. this._tempInfluences[influenceCount++] = target.influence;
  83462. var positions = target.getPositions();
  83463. if (positions) {
  83464. this._supportsNormals = this._supportsNormals && target.hasNormals;
  83465. this._supportsTangents = this._supportsTangents && target.hasTangents;
  83466. var vertexCount = positions.length / 3;
  83467. if (this._vertexCount === 0) {
  83468. this._vertexCount = vertexCount;
  83469. }
  83470. else if (this._vertexCount !== vertexCount) {
  83471. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  83472. return;
  83473. }
  83474. }
  83475. }
  83476. if (!this._influences || this._influences.length !== influenceCount) {
  83477. this._influences = new Float32Array(influenceCount);
  83478. }
  83479. for (var index = 0; index < influenceCount; index++) {
  83480. this._influences[index] = this._tempInfluences[index];
  83481. }
  83482. if (needUpdate && this._scene) {
  83483. // Flag meshes as dirty to resync with the active targets
  83484. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  83485. var mesh = _c[_b];
  83486. if (mesh.morphTargetManager === this) {
  83487. mesh._syncGeometryWithMorphTargetManager();
  83488. }
  83489. }
  83490. }
  83491. };
  83492. // Statics
  83493. MorphTargetManager.Parse = function (serializationObject, scene) {
  83494. var result = new MorphTargetManager(scene);
  83495. result._uniqueId = serializationObject.id;
  83496. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  83497. var targetData = _a[_i];
  83498. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  83499. }
  83500. return result;
  83501. };
  83502. return MorphTargetManager;
  83503. }());
  83504. BABYLON.MorphTargetManager = MorphTargetManager;
  83505. })(BABYLON || (BABYLON = {}));
  83506. //# sourceMappingURL=babylon.morphTargetManager.js.map
  83507. "use strict";
  83508. var BABYLON;
  83509. (function (BABYLON) {
  83510. var Octree = /** @class */ (function () {
  83511. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  83512. if (maxDepth === void 0) { maxDepth = 2; }
  83513. this.maxDepth = maxDepth;
  83514. this.dynamicContent = new Array();
  83515. this._maxBlockCapacity = maxBlockCapacity || 64;
  83516. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  83517. this._creationFunc = creationFunc;
  83518. }
  83519. // Methods
  83520. Octree.prototype.update = function (worldMin, worldMax, entries) {
  83521. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  83522. };
  83523. Octree.prototype.addMesh = function (entry) {
  83524. for (var index = 0; index < this.blocks.length; index++) {
  83525. var block = this.blocks[index];
  83526. block.addEntry(entry);
  83527. }
  83528. };
  83529. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  83530. this._selectionContent.reset();
  83531. for (var index = 0; index < this.blocks.length; index++) {
  83532. var block = this.blocks[index];
  83533. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  83534. }
  83535. if (allowDuplicate) {
  83536. this._selectionContent.concat(this.dynamicContent);
  83537. }
  83538. else {
  83539. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  83540. }
  83541. return this._selectionContent;
  83542. };
  83543. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  83544. this._selectionContent.reset();
  83545. for (var index = 0; index < this.blocks.length; index++) {
  83546. var block = this.blocks[index];
  83547. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  83548. }
  83549. if (allowDuplicate) {
  83550. this._selectionContent.concat(this.dynamicContent);
  83551. }
  83552. else {
  83553. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  83554. }
  83555. return this._selectionContent;
  83556. };
  83557. Octree.prototype.intersectsRay = function (ray) {
  83558. this._selectionContent.reset();
  83559. for (var index = 0; index < this.blocks.length; index++) {
  83560. var block = this.blocks[index];
  83561. block.intersectsRay(ray, this._selectionContent);
  83562. }
  83563. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  83564. return this._selectionContent;
  83565. };
  83566. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  83567. target.blocks = new Array();
  83568. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  83569. // Segmenting space
  83570. for (var x = 0; x < 2; x++) {
  83571. for (var y = 0; y < 2; y++) {
  83572. for (var z = 0; z < 2; z++) {
  83573. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  83574. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  83575. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  83576. block.addEntries(entries);
  83577. target.blocks.push(block);
  83578. }
  83579. }
  83580. }
  83581. };
  83582. Octree.CreationFuncForMeshes = function (entry, block) {
  83583. var boundingInfo = entry.getBoundingInfo();
  83584. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  83585. block.entries.push(entry);
  83586. }
  83587. };
  83588. Octree.CreationFuncForSubMeshes = function (entry, block) {
  83589. var boundingInfo = entry.getBoundingInfo();
  83590. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  83591. block.entries.push(entry);
  83592. }
  83593. };
  83594. return Octree;
  83595. }());
  83596. BABYLON.Octree = Octree;
  83597. })(BABYLON || (BABYLON = {}));
  83598. //# sourceMappingURL=babylon.octree.js.map
  83599. "use strict";
  83600. var BABYLON;
  83601. (function (BABYLON) {
  83602. var OctreeBlock = /** @class */ (function () {
  83603. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  83604. this.entries = new Array();
  83605. this._boundingVectors = new Array();
  83606. this._capacity = capacity;
  83607. this._depth = depth;
  83608. this._maxDepth = maxDepth;
  83609. this._creationFunc = creationFunc;
  83610. this._minPoint = minPoint;
  83611. this._maxPoint = maxPoint;
  83612. this._boundingVectors.push(minPoint.clone());
  83613. this._boundingVectors.push(maxPoint.clone());
  83614. this._boundingVectors.push(minPoint.clone());
  83615. this._boundingVectors[2].x = maxPoint.x;
  83616. this._boundingVectors.push(minPoint.clone());
  83617. this._boundingVectors[3].y = maxPoint.y;
  83618. this._boundingVectors.push(minPoint.clone());
  83619. this._boundingVectors[4].z = maxPoint.z;
  83620. this._boundingVectors.push(maxPoint.clone());
  83621. this._boundingVectors[5].z = minPoint.z;
  83622. this._boundingVectors.push(maxPoint.clone());
  83623. this._boundingVectors[6].x = minPoint.x;
  83624. this._boundingVectors.push(maxPoint.clone());
  83625. this._boundingVectors[7].y = minPoint.y;
  83626. }
  83627. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  83628. // Property
  83629. get: function () {
  83630. return this._capacity;
  83631. },
  83632. enumerable: true,
  83633. configurable: true
  83634. });
  83635. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  83636. get: function () {
  83637. return this._minPoint;
  83638. },
  83639. enumerable: true,
  83640. configurable: true
  83641. });
  83642. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  83643. get: function () {
  83644. return this._maxPoint;
  83645. },
  83646. enumerable: true,
  83647. configurable: true
  83648. });
  83649. // Methods
  83650. OctreeBlock.prototype.addEntry = function (entry) {
  83651. if (this.blocks) {
  83652. for (var index = 0; index < this.blocks.length; index++) {
  83653. var block = this.blocks[index];
  83654. block.addEntry(entry);
  83655. }
  83656. return;
  83657. }
  83658. this._creationFunc(entry, this);
  83659. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  83660. this.createInnerBlocks();
  83661. }
  83662. };
  83663. OctreeBlock.prototype.addEntries = function (entries) {
  83664. for (var index = 0; index < entries.length; index++) {
  83665. var mesh = entries[index];
  83666. this.addEntry(mesh);
  83667. }
  83668. };
  83669. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  83670. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  83671. if (this.blocks) {
  83672. for (var index = 0; index < this.blocks.length; index++) {
  83673. var block = this.blocks[index];
  83674. block.select(frustumPlanes, selection, allowDuplicate);
  83675. }
  83676. return;
  83677. }
  83678. if (allowDuplicate) {
  83679. selection.concat(this.entries);
  83680. }
  83681. else {
  83682. selection.concatWithNoDuplicate(this.entries);
  83683. }
  83684. }
  83685. };
  83686. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  83687. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  83688. if (this.blocks) {
  83689. for (var index = 0; index < this.blocks.length; index++) {
  83690. var block = this.blocks[index];
  83691. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  83692. }
  83693. return;
  83694. }
  83695. if (allowDuplicate) {
  83696. selection.concat(this.entries);
  83697. }
  83698. else {
  83699. selection.concatWithNoDuplicate(this.entries);
  83700. }
  83701. }
  83702. };
  83703. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  83704. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  83705. if (this.blocks) {
  83706. for (var index = 0; index < this.blocks.length; index++) {
  83707. var block = this.blocks[index];
  83708. block.intersectsRay(ray, selection);
  83709. }
  83710. return;
  83711. }
  83712. selection.concatWithNoDuplicate(this.entries);
  83713. }
  83714. };
  83715. OctreeBlock.prototype.createInnerBlocks = function () {
  83716. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  83717. };
  83718. return OctreeBlock;
  83719. }());
  83720. BABYLON.OctreeBlock = OctreeBlock;
  83721. })(BABYLON || (BABYLON = {}));
  83722. //# sourceMappingURL=babylon.octreeBlock.js.map
  83723. "use strict";
  83724. var BABYLON;
  83725. (function (BABYLON) {
  83726. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  83727. __extends(VRDistortionCorrectionPostProcess, _super);
  83728. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  83729. var _this = _super.call(this, name, "vrDistortionCorrection", [
  83730. 'LensCenter',
  83731. 'Scale',
  83732. 'ScaleIn',
  83733. 'HmdWarpParam'
  83734. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  83735. _this._isRightEye = isRightEye;
  83736. _this._distortionFactors = vrMetrics.distortionK;
  83737. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  83738. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  83739. _this.adaptScaleToCurrentViewport = true;
  83740. _this.onSizeChangedObservable.add(function () {
  83741. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  83742. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  83743. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  83744. });
  83745. _this.onApplyObservable.add(function (effect) {
  83746. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  83747. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  83748. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  83749. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  83750. });
  83751. return _this;
  83752. }
  83753. return VRDistortionCorrectionPostProcess;
  83754. }(BABYLON.PostProcess));
  83755. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  83756. })(BABYLON || (BABYLON = {}));
  83757. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  83758. "use strict";
  83759. var BABYLON;
  83760. (function (BABYLON) {
  83761. var AnaglyphPostProcess = /** @class */ (function (_super) {
  83762. __extends(AnaglyphPostProcess, _super);
  83763. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  83764. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  83765. _this._passedProcess = rigCameras[0]._rigPostProcess;
  83766. _this.onApplyObservable.add(function (effect) {
  83767. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  83768. });
  83769. return _this;
  83770. }
  83771. return AnaglyphPostProcess;
  83772. }(BABYLON.PostProcess));
  83773. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  83774. })(BABYLON || (BABYLON = {}));
  83775. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  83776. "use strict";
  83777. var BABYLON;
  83778. (function (BABYLON) {
  83779. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  83780. __extends(StereoscopicInterlacePostProcess, _super);
  83781. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  83782. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  83783. _this._passedProcess = rigCameras[0]._rigPostProcess;
  83784. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  83785. _this.onSizeChangedObservable.add(function () {
  83786. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  83787. });
  83788. _this.onApplyObservable.add(function (effect) {
  83789. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  83790. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  83791. });
  83792. return _this;
  83793. }
  83794. return StereoscopicInterlacePostProcess;
  83795. }(BABYLON.PostProcess));
  83796. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  83797. })(BABYLON || (BABYLON = {}));
  83798. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  83799. "use strict";
  83800. var BABYLON;
  83801. (function (BABYLON) {
  83802. /**
  83803. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  83804. * Screen rotation is taken into account.
  83805. */
  83806. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  83807. function FreeCameraDeviceOrientationInput() {
  83808. var _this = this;
  83809. this._screenOrientationAngle = 0;
  83810. this._screenQuaternion = new BABYLON.Quaternion();
  83811. this._alpha = 0;
  83812. this._beta = 0;
  83813. this._gamma = 0;
  83814. this._orientationChanged = function () {
  83815. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  83816. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  83817. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  83818. };
  83819. this._deviceOrientation = function (evt) {
  83820. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  83821. _this._beta = evt.beta !== null ? evt.beta : 0;
  83822. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  83823. };
  83824. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  83825. this._orientationChanged();
  83826. }
  83827. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  83828. get: function () {
  83829. return this._camera;
  83830. },
  83831. set: function (camera) {
  83832. this._camera = camera;
  83833. if (this._camera != null && !this._camera.rotationQuaternion) {
  83834. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  83835. }
  83836. },
  83837. enumerable: true,
  83838. configurable: true
  83839. });
  83840. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  83841. window.addEventListener("orientationchange", this._orientationChanged);
  83842. window.addEventListener("deviceorientation", this._deviceOrientation);
  83843. //In certain cases, the attach control is called AFTER orientation was changed,
  83844. //So this is needed.
  83845. this._orientationChanged();
  83846. };
  83847. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  83848. window.removeEventListener("orientationchange", this._orientationChanged);
  83849. window.removeEventListener("deviceorientation", this._deviceOrientation);
  83850. };
  83851. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  83852. //if no device orientation provided, don't update the rotation.
  83853. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  83854. if (!this._alpha)
  83855. return;
  83856. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  83857. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  83858. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  83859. //Mirror on XY Plane
  83860. this._camera.rotationQuaternion.z *= -1;
  83861. this._camera.rotationQuaternion.w *= -1;
  83862. };
  83863. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  83864. return "FreeCameraDeviceOrientationInput";
  83865. };
  83866. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  83867. return "deviceOrientation";
  83868. };
  83869. return FreeCameraDeviceOrientationInput;
  83870. }());
  83871. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  83872. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  83873. })(BABYLON || (BABYLON = {}));
  83874. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  83875. "use strict";
  83876. var BABYLON;
  83877. (function (BABYLON) {
  83878. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  83879. function ArcRotateCameraVRDeviceOrientationInput() {
  83880. this.alphaCorrection = 1;
  83881. this.betaCorrection = 1;
  83882. this.gammaCorrection = 1;
  83883. this._alpha = 0;
  83884. this._gamma = 0;
  83885. this._dirty = false;
  83886. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  83887. }
  83888. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  83889. this.camera.attachControl(element, noPreventDefault);
  83890. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  83891. };
  83892. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  83893. if (evt.alpha !== null) {
  83894. this._alpha = +evt.alpha | 0;
  83895. }
  83896. if (evt.gamma !== null) {
  83897. this._gamma = +evt.gamma | 0;
  83898. }
  83899. this._dirty = true;
  83900. };
  83901. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  83902. if (this._dirty) {
  83903. this._dirty = false;
  83904. if (this._gamma < 0) {
  83905. this._gamma = 180 + this._gamma;
  83906. }
  83907. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  83908. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  83909. }
  83910. };
  83911. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  83912. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  83913. };
  83914. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  83915. return "ArcRotateCameraVRDeviceOrientationInput";
  83916. };
  83917. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  83918. return "VRDeviceOrientation";
  83919. };
  83920. return ArcRotateCameraVRDeviceOrientationInput;
  83921. }());
  83922. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  83923. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  83924. })(BABYLON || (BABYLON = {}));
  83925. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  83926. "use strict";
  83927. var BABYLON;
  83928. (function (BABYLON) {
  83929. var VRCameraMetrics = /** @class */ (function () {
  83930. function VRCameraMetrics() {
  83931. this.compensateDistortion = true;
  83932. }
  83933. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  83934. get: function () {
  83935. return this.hResolution / (2 * this.vResolution);
  83936. },
  83937. enumerable: true,
  83938. configurable: true
  83939. });
  83940. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  83941. get: function () {
  83942. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  83943. },
  83944. enumerable: true,
  83945. configurable: true
  83946. });
  83947. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  83948. get: function () {
  83949. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  83950. var h = (4 * meters) / this.hScreenSize;
  83951. return BABYLON.Matrix.Translation(h, 0, 0);
  83952. },
  83953. enumerable: true,
  83954. configurable: true
  83955. });
  83956. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  83957. get: function () {
  83958. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  83959. var h = (4 * meters) / this.hScreenSize;
  83960. return BABYLON.Matrix.Translation(-h, 0, 0);
  83961. },
  83962. enumerable: true,
  83963. configurable: true
  83964. });
  83965. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  83966. get: function () {
  83967. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  83968. },
  83969. enumerable: true,
  83970. configurable: true
  83971. });
  83972. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  83973. get: function () {
  83974. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  83975. },
  83976. enumerable: true,
  83977. configurable: true
  83978. });
  83979. VRCameraMetrics.GetDefault = function () {
  83980. var result = new VRCameraMetrics();
  83981. result.hResolution = 1280;
  83982. result.vResolution = 800;
  83983. result.hScreenSize = 0.149759993;
  83984. result.vScreenSize = 0.0935999975;
  83985. result.vScreenCenter = 0.0467999987;
  83986. result.eyeToScreenDistance = 0.0410000011;
  83987. result.lensSeparationDistance = 0.0635000020;
  83988. result.interpupillaryDistance = 0.0640000030;
  83989. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  83990. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  83991. result.postProcessScaleFactor = 1.714605507808412;
  83992. result.lensCenterOffset = 0.151976421;
  83993. return result;
  83994. };
  83995. return VRCameraMetrics;
  83996. }());
  83997. BABYLON.VRCameraMetrics = VRCameraMetrics;
  83998. })(BABYLON || (BABYLON = {}));
  83999. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  84000. "use strict";
  84001. var BABYLON;
  84002. (function (BABYLON) {
  84003. /**
  84004. * This represents a WebVR camera.
  84005. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  84006. * @example http://doc.babylonjs.com/how_to/webvr_camera
  84007. */
  84008. var WebVRFreeCamera = /** @class */ (function (_super) {
  84009. __extends(WebVRFreeCamera, _super);
  84010. /**
  84011. * Instantiates a WebVRFreeCamera.
  84012. * @param name The name of the WebVRFreeCamera
  84013. * @param position The starting anchor position for the camera
  84014. * @param scene The scene the camera belongs to
  84015. * @param webVROptions a set of customizable options for the webVRCamera
  84016. */
  84017. function WebVRFreeCamera(name, position, scene, webVROptions) {
  84018. if (webVROptions === void 0) { webVROptions = {}; }
  84019. var _this = _super.call(this, name, position, scene) || this;
  84020. _this.webVROptions = webVROptions;
  84021. /**
  84022. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  84023. */
  84024. _this._vrDevice = null;
  84025. /**
  84026. * The rawPose of the vrDevice.
  84027. */
  84028. _this.rawPose = null;
  84029. _this._specsVersion = "1.1";
  84030. _this._attached = false;
  84031. _this._descendants = [];
  84032. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  84033. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  84034. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  84035. _this._standingMatrix = null;
  84036. /**
  84037. * Represents device position in babylon space.
  84038. */
  84039. _this.devicePosition = BABYLON.Vector3.Zero();
  84040. /**
  84041. * Represents device rotation in babylon space.
  84042. */
  84043. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  84044. /**
  84045. * The scale of the device to be used when translating from device space to babylon space.
  84046. */
  84047. _this.deviceScaleFactor = 1;
  84048. _this._deviceToWorld = BABYLON.Matrix.Identity();
  84049. _this._worldToDevice = BABYLON.Matrix.Identity();
  84050. /**
  84051. * References to the webVR controllers for the vrDevice.
  84052. */
  84053. _this.controllers = [];
  84054. /**
  84055. * Emits an event when a controller is attached.
  84056. */
  84057. _this.onControllersAttachedObservable = new BABYLON.Observable();
  84058. /**
  84059. * Emits an event when a controller's mesh has been loaded;
  84060. */
  84061. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  84062. /**
  84063. * If the rig cameras be used as parent instead of this camera.
  84064. */
  84065. _this.rigParenting = true;
  84066. _this._defaultHeight = undefined;
  84067. _this._workingVector = BABYLON.Vector3.Zero();
  84068. _this._oneVector = BABYLON.Vector3.One();
  84069. _this._workingMatrix = BABYLON.Matrix.Identity();
  84070. _this._cache.position = BABYLON.Vector3.Zero();
  84071. if (webVROptions.defaultHeight) {
  84072. _this._defaultHeight = webVROptions.defaultHeight;
  84073. _this.position.y = _this._defaultHeight;
  84074. }
  84075. _this.minZ = 0.1;
  84076. //legacy support - the compensation boolean was removed.
  84077. if (arguments.length === 5) {
  84078. _this.webVROptions = arguments[4];
  84079. }
  84080. // default webVR options
  84081. if (_this.webVROptions.trackPosition == undefined) {
  84082. _this.webVROptions.trackPosition = true;
  84083. }
  84084. if (_this.webVROptions.controllerMeshes == undefined) {
  84085. _this.webVROptions.controllerMeshes = true;
  84086. }
  84087. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  84088. _this.webVROptions.defaultLightingOnControllers = true;
  84089. }
  84090. _this.rotationQuaternion = new BABYLON.Quaternion();
  84091. if (_this.webVROptions && _this.webVROptions.positionScale) {
  84092. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  84093. }
  84094. //enable VR
  84095. var engine = _this.getEngine();
  84096. _this._onVREnabled = function (success) { if (success) {
  84097. _this.initControllers();
  84098. } };
  84099. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  84100. engine.initWebVR().add(function (event) {
  84101. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  84102. return;
  84103. }
  84104. _this._vrDevice = event.vrDisplay;
  84105. //reset the rig parameters.
  84106. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  84107. if (_this._attached) {
  84108. _this.getEngine().enableVR();
  84109. }
  84110. });
  84111. if (typeof (VRFrameData) !== "undefined")
  84112. _this._frameData = new VRFrameData();
  84113. /**
  84114. * The idea behind the following lines:
  84115. * objects that have the camera as parent should actually have the rig cameras as a parent.
  84116. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  84117. * the second will not show it correctly.
  84118. *
  84119. * To solve this - each object that has the camera as parent will be added to a protected array.
  84120. * When the rig camera renders, it will take this array and set all of those to be its children.
  84121. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  84122. * Amazing!
  84123. */
  84124. scene.onBeforeCameraRenderObservable.add(function (camera) {
  84125. if (camera.parent === _this && _this.rigParenting) {
  84126. _this._descendants = _this.getDescendants(true, function (n) {
  84127. // don't take the cameras or the controllers!
  84128. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  84129. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  84130. return !isController && !isRigCamera;
  84131. });
  84132. _this._descendants.forEach(function (node) {
  84133. node.parent = camera;
  84134. });
  84135. }
  84136. });
  84137. scene.onAfterCameraRenderObservable.add(function (camera) {
  84138. if (camera.parent === _this && _this.rigParenting) {
  84139. _this._descendants.forEach(function (node) {
  84140. node.parent = _this;
  84141. });
  84142. }
  84143. });
  84144. return _this;
  84145. }
  84146. /**
  84147. * Gets the device distance from the ground in meters.
  84148. * @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.
  84149. */
  84150. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  84151. if (this._standingMatrix) {
  84152. // Add standing matrix offset to get real offset from ground in room
  84153. this._standingMatrix.getTranslationToRef(this._workingVector);
  84154. return this._deviceRoomPosition.y + this._workingVector.y;
  84155. }
  84156. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  84157. return this._defaultHeight || 0;
  84158. };
  84159. /**
  84160. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  84161. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  84162. */
  84163. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  84164. var _this = this;
  84165. if (callback === void 0) { callback = function (bool) { }; }
  84166. // Use standing matrix if available
  84167. this.getEngine().initWebVRAsync().then(function (result) {
  84168. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  84169. callback(false);
  84170. }
  84171. else {
  84172. _this._standingMatrix = new BABYLON.Matrix();
  84173. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  84174. if (!_this.getScene().useRightHandedSystem) {
  84175. [2, 6, 8, 9, 14].forEach(function (num) {
  84176. if (_this._standingMatrix) {
  84177. _this._standingMatrix.m[num] *= -1;
  84178. }
  84179. });
  84180. }
  84181. callback(true);
  84182. }
  84183. });
  84184. };
  84185. /**
  84186. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  84187. * @returns A promise with a boolean set to if the standing matrix is supported.
  84188. */
  84189. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  84190. var _this = this;
  84191. return new Promise(function (res, rej) {
  84192. _this.useStandingMatrix(function (supported) {
  84193. res(supported);
  84194. });
  84195. });
  84196. };
  84197. /**
  84198. * Disposes the camera
  84199. */
  84200. WebVRFreeCamera.prototype.dispose = function () {
  84201. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  84202. _super.prototype.dispose.call(this);
  84203. };
  84204. /**
  84205. * Gets a vrController by name.
  84206. * @param name The name of the controller to retreive
  84207. * @returns the controller matching the name specified or null if not found
  84208. */
  84209. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  84210. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  84211. var gp = _a[_i];
  84212. if (gp.hand === name) {
  84213. return gp;
  84214. }
  84215. }
  84216. return null;
  84217. };
  84218. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  84219. /**
  84220. * The controller corrisponding to the users left hand.
  84221. */
  84222. get: function () {
  84223. if (!this._leftController) {
  84224. this._leftController = this.getControllerByName("left");
  84225. }
  84226. return this._leftController;
  84227. },
  84228. enumerable: true,
  84229. configurable: true
  84230. });
  84231. ;
  84232. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  84233. /**
  84234. * The controller corrisponding to the users right hand.
  84235. */
  84236. get: function () {
  84237. if (!this._rightController) {
  84238. this._rightController = this.getControllerByName("right");
  84239. }
  84240. return this._rightController;
  84241. },
  84242. enumerable: true,
  84243. configurable: true
  84244. });
  84245. ;
  84246. /**
  84247. * Casts a ray forward from the vrCamera's gaze.
  84248. * @param length Length of the ray (default: 100)
  84249. * @returns the ray corrisponding to the gaze
  84250. */
  84251. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  84252. if (length === void 0) { length = 100; }
  84253. if (this.leftCamera) {
  84254. // Use left eye to avoid computation to compute center on every call
  84255. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  84256. }
  84257. else {
  84258. return _super.prototype.getForwardRay.call(this, length);
  84259. }
  84260. };
  84261. /**
  84262. * Updates the camera based on device's frame data
  84263. */
  84264. WebVRFreeCamera.prototype._checkInputs = function () {
  84265. if (this._vrDevice && this._vrDevice.isPresenting) {
  84266. this._vrDevice.getFrameData(this._frameData);
  84267. this.updateFromDevice(this._frameData.pose);
  84268. }
  84269. _super.prototype._checkInputs.call(this);
  84270. };
  84271. /**
  84272. * Updates the poseControlled values based on the input device pose.
  84273. * @param poseData Pose coming from the device
  84274. */
  84275. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  84276. if (poseData && poseData.orientation) {
  84277. this.rawPose = poseData;
  84278. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  84279. if (this.getScene().useRightHandedSystem) {
  84280. this._deviceRoomRotationQuaternion.z *= -1;
  84281. this._deviceRoomRotationQuaternion.w *= -1;
  84282. }
  84283. if (this.webVROptions.trackPosition && this.rawPose.position) {
  84284. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  84285. if (this.getScene().useRightHandedSystem) {
  84286. this._deviceRoomPosition.z *= -1;
  84287. }
  84288. }
  84289. }
  84290. };
  84291. /**
  84292. * WebVR's attach control will start broadcasting frames to the device.
  84293. * Note that in certain browsers (chrome for example) this function must be called
  84294. * within a user-interaction callback. Example:
  84295. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  84296. *
  84297. * @param element html element to attach the vrDevice to
  84298. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  84299. */
  84300. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  84301. _super.prototype.attachControl.call(this, element, noPreventDefault);
  84302. this._attached = true;
  84303. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  84304. if (this._vrDevice) {
  84305. this.getEngine().enableVR();
  84306. }
  84307. };
  84308. /**
  84309. * Detaches the camera from the html element and disables VR
  84310. *
  84311. * @param element html element to detach from
  84312. */
  84313. WebVRFreeCamera.prototype.detachControl = function (element) {
  84314. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  84315. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  84316. _super.prototype.detachControl.call(this, element);
  84317. this._attached = false;
  84318. this.getEngine().disableVR();
  84319. };
  84320. /**
  84321. * @returns the name of this class
  84322. */
  84323. WebVRFreeCamera.prototype.getClassName = function () {
  84324. return "WebVRFreeCamera";
  84325. };
  84326. /**
  84327. * Calls resetPose on the vrDisplay
  84328. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  84329. */
  84330. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  84331. //uses the vrDisplay's "resetPose()".
  84332. //pitch and roll won't be affected.
  84333. this._vrDevice.resetPose();
  84334. };
  84335. /**
  84336. * Updates the rig cameras (left and right eye)
  84337. */
  84338. WebVRFreeCamera.prototype._updateRigCameras = function () {
  84339. var camLeft = this._rigCameras[0];
  84340. var camRight = this._rigCameras[1];
  84341. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  84342. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  84343. camLeft.position.copyFrom(this._deviceRoomPosition);
  84344. camRight.position.copyFrom(this._deviceRoomPosition);
  84345. };
  84346. /**
  84347. * Updates the cached values of the camera
  84348. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  84349. */
  84350. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  84351. var _this = this;
  84352. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  84353. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  84354. if (!this.updateCacheCalled) {
  84355. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  84356. this.updateCacheCalled = true;
  84357. this.update();
  84358. }
  84359. // Set working vector to the device position in room space rotated by the new rotation
  84360. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  84361. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  84362. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  84363. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  84364. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  84365. // Add translation from anchor position
  84366. this._deviceToWorld.getTranslationToRef(this._workingVector);
  84367. this._workingVector.addInPlace(this.position);
  84368. this._workingVector.subtractInPlace(this._cache.position);
  84369. this._deviceToWorld.setTranslation(this._workingVector);
  84370. // Set an inverted matrix to be used when updating the camera
  84371. this._deviceToWorld.invertToRef(this._worldToDevice);
  84372. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  84373. this.controllers.forEach(function (controller) {
  84374. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  84375. controller.update();
  84376. });
  84377. }
  84378. if (!ignoreParentClass) {
  84379. _super.prototype._updateCache.call(this);
  84380. }
  84381. this.updateCacheCalled = false;
  84382. };
  84383. /**
  84384. * Updates the current device position and rotation in the babylon world
  84385. */
  84386. WebVRFreeCamera.prototype.update = function () {
  84387. // Get current device position in babylon world
  84388. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  84389. // Get current device rotation in babylon world
  84390. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  84391. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  84392. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  84393. _super.prototype.update.call(this);
  84394. };
  84395. /**
  84396. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  84397. * @returns an identity matrix
  84398. */
  84399. WebVRFreeCamera.prototype._getViewMatrix = function () {
  84400. return BABYLON.Matrix.Identity();
  84401. };
  84402. /**
  84403. * This function is called by the two RIG cameras.
  84404. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  84405. */
  84406. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  84407. var _this = this;
  84408. // Update the parent camera prior to using a child camera to avoid desynchronization
  84409. var parentCamera = this._cameraRigParams["parentCamera"];
  84410. parentCamera._updateCache();
  84411. //WebVR 1.1
  84412. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  84413. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  84414. if (!this.getScene().useRightHandedSystem) {
  84415. [2, 6, 8, 9, 14].forEach(function (num) {
  84416. _this._webvrViewMatrix.m[num] *= -1;
  84417. });
  84418. }
  84419. // update the camera rotation matrix
  84420. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  84421. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  84422. // Computing target and final matrix
  84423. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  84424. // should the view matrix be updated with scale and position offset?
  84425. if (parentCamera.deviceScaleFactor !== 1) {
  84426. this._webvrViewMatrix.invert();
  84427. // scale the position, if set
  84428. if (parentCamera.deviceScaleFactor) {
  84429. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  84430. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  84431. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  84432. }
  84433. this._webvrViewMatrix.invert();
  84434. }
  84435. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  84436. return this._webvrViewMatrix;
  84437. };
  84438. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  84439. var _this = this;
  84440. var parentCamera = this.parent;
  84441. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  84442. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  84443. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  84444. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  84445. //babylon compatible matrix
  84446. if (!this.getScene().useRightHandedSystem) {
  84447. [8, 9, 10, 11].forEach(function (num) {
  84448. _this._projectionMatrix.m[num] *= -1;
  84449. });
  84450. }
  84451. return this._projectionMatrix;
  84452. };
  84453. /**
  84454. * Initializes the controllers and their meshes
  84455. */
  84456. WebVRFreeCamera.prototype.initControllers = function () {
  84457. var _this = this;
  84458. this.controllers = [];
  84459. var manager = this.getScene().gamepadManager;
  84460. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  84461. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  84462. var webVrController = gamepad;
  84463. if (webVrController.defaultModel) {
  84464. webVrController.defaultModel.setEnabled(false);
  84465. }
  84466. if (webVrController.hand === "right") {
  84467. _this._rightController = null;
  84468. }
  84469. if (webVrController.hand === "left") {
  84470. _this._leftController = null;
  84471. }
  84472. var controllerIndex = _this.controllers.indexOf(webVrController);
  84473. if (controllerIndex !== -1) {
  84474. _this.controllers.splice(controllerIndex, 1);
  84475. }
  84476. }
  84477. });
  84478. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  84479. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  84480. var webVrController_1 = gamepad;
  84481. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  84482. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  84483. if (_this.webVROptions.controllerMeshes) {
  84484. if (webVrController_1.defaultModel) {
  84485. webVrController_1.defaultModel.setEnabled(true);
  84486. }
  84487. else {
  84488. // Load the meshes
  84489. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  84490. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  84491. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  84492. if (_this.webVROptions.defaultLightingOnControllers) {
  84493. if (!_this._lightOnControllers) {
  84494. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  84495. }
  84496. var activateLightOnSubMeshes_1 = function (mesh, light) {
  84497. var children = mesh.getChildren();
  84498. if (children.length !== 0) {
  84499. children.forEach(function (mesh) {
  84500. light.includedOnlyMeshes.push(mesh);
  84501. activateLightOnSubMeshes_1(mesh, light);
  84502. });
  84503. }
  84504. };
  84505. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  84506. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  84507. }
  84508. });
  84509. }
  84510. }
  84511. webVrController_1.attachToPoseControlledCamera(_this);
  84512. // since this is async - sanity check. Is the controller already stored?
  84513. if (_this.controllers.indexOf(webVrController_1) === -1) {
  84514. //add to the controllers array
  84515. _this.controllers.push(webVrController_1);
  84516. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  84517. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  84518. // So we're overriding setting left & right manually to be sure
  84519. var firstViveWandDetected = false;
  84520. for (var i = 0; i < _this.controllers.length; i++) {
  84521. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  84522. if (!firstViveWandDetected) {
  84523. firstViveWandDetected = true;
  84524. _this.controllers[i].hand = "left";
  84525. }
  84526. else {
  84527. _this.controllers[i].hand = "right";
  84528. }
  84529. }
  84530. }
  84531. //did we find enough controllers? Great! let the developer know.
  84532. if (_this.controllers.length >= 2) {
  84533. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  84534. }
  84535. }
  84536. }
  84537. });
  84538. };
  84539. return WebVRFreeCamera;
  84540. }(BABYLON.FreeCamera));
  84541. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  84542. })(BABYLON || (BABYLON = {}));
  84543. //# sourceMappingURL=babylon.webVRCamera.js.map
  84544. "use strict";
  84545. var BABYLON;
  84546. (function (BABYLON) {
  84547. // We're mainly based on the logic defined into the FreeCamera code
  84548. /**
  84549. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  84550. * being tilted forward or back and left or right.
  84551. */
  84552. var DeviceOrientationCamera = /** @class */ (function (_super) {
  84553. __extends(DeviceOrientationCamera, _super);
  84554. /**
  84555. * Creates a new device orientation camera
  84556. * @param name The name of the camera
  84557. * @param position The start position camera
  84558. * @param scene The scene the camera belongs to
  84559. */
  84560. function DeviceOrientationCamera(name, position, scene) {
  84561. var _this = _super.call(this, name, position, scene) || this;
  84562. _this._quaternionCache = new BABYLON.Quaternion();
  84563. _this.inputs.addDeviceOrientation();
  84564. return _this;
  84565. }
  84566. /**
  84567. * Gets the current instance class name ("DeviceOrientationCamera").
  84568. * This helps avoiding instanceof at run time.
  84569. * @returns the class name
  84570. */
  84571. DeviceOrientationCamera.prototype.getClassName = function () {
  84572. return "DeviceOrientationCamera";
  84573. };
  84574. /**
  84575. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  84576. */
  84577. DeviceOrientationCamera.prototype._checkInputs = function () {
  84578. _super.prototype._checkInputs.call(this);
  84579. this._quaternionCache.copyFrom(this.rotationQuaternion);
  84580. if (this._initialQuaternion) {
  84581. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  84582. }
  84583. };
  84584. /**
  84585. * Reset the camera to its default orientation on the specified axis only.
  84586. * @param axis The axis to reset
  84587. */
  84588. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  84589. var _this = this;
  84590. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  84591. //can only work if this camera has a rotation quaternion already.
  84592. if (!this.rotationQuaternion)
  84593. return;
  84594. if (!this._initialQuaternion) {
  84595. this._initialQuaternion = new BABYLON.Quaternion();
  84596. }
  84597. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  84598. ['x', 'y', 'z'].forEach(function (axisName) {
  84599. if (!axis[axisName]) {
  84600. _this._initialQuaternion[axisName] = 0;
  84601. }
  84602. else {
  84603. _this._initialQuaternion[axisName] *= -1;
  84604. }
  84605. });
  84606. this._initialQuaternion.normalize();
  84607. //force rotation update
  84608. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  84609. };
  84610. return DeviceOrientationCamera;
  84611. }(BABYLON.FreeCamera));
  84612. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  84613. })(BABYLON || (BABYLON = {}));
  84614. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  84615. "use strict";
  84616. var BABYLON;
  84617. (function (BABYLON) {
  84618. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  84619. __extends(VRDeviceOrientationFreeCamera, _super);
  84620. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  84621. if (compensateDistortion === void 0) { compensateDistortion = true; }
  84622. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  84623. var _this = _super.call(this, name, position, scene) || this;
  84624. vrCameraMetrics.compensateDistortion = compensateDistortion;
  84625. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  84626. return _this;
  84627. }
  84628. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  84629. return "VRDeviceOrientationFreeCamera";
  84630. };
  84631. return VRDeviceOrientationFreeCamera;
  84632. }(BABYLON.DeviceOrientationCamera));
  84633. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  84634. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  84635. __extends(VRDeviceOrientationGamepadCamera, _super);
  84636. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  84637. if (compensateDistortion === void 0) { compensateDistortion = true; }
  84638. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  84639. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  84640. _this.inputs.addGamepad();
  84641. return _this;
  84642. }
  84643. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  84644. return "VRDeviceOrientationGamepadCamera";
  84645. };
  84646. return VRDeviceOrientationGamepadCamera;
  84647. }(VRDeviceOrientationFreeCamera));
  84648. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  84649. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  84650. __extends(VRDeviceOrientationArcRotateCamera, _super);
  84651. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  84652. if (compensateDistortion === void 0) { compensateDistortion = true; }
  84653. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  84654. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  84655. vrCameraMetrics.compensateDistortion = compensateDistortion;
  84656. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  84657. _this.inputs.addVRDeviceOrientation();
  84658. return _this;
  84659. }
  84660. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  84661. return "VRDeviceOrientationArcRotateCamera";
  84662. };
  84663. return VRDeviceOrientationArcRotateCamera;
  84664. }(BABYLON.ArcRotateCamera));
  84665. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  84666. })(BABYLON || (BABYLON = {}));
  84667. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  84668. "use strict";
  84669. var BABYLON;
  84670. (function (BABYLON) {
  84671. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  84672. __extends(AnaglyphFreeCamera, _super);
  84673. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  84674. var _this = _super.call(this, name, position, scene) || this;
  84675. _this.interaxialDistance = interaxialDistance;
  84676. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  84677. return _this;
  84678. }
  84679. AnaglyphFreeCamera.prototype.getClassName = function () {
  84680. return "AnaglyphFreeCamera";
  84681. };
  84682. return AnaglyphFreeCamera;
  84683. }(BABYLON.FreeCamera));
  84684. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  84685. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  84686. __extends(AnaglyphArcRotateCamera, _super);
  84687. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  84688. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  84689. _this.interaxialDistance = interaxialDistance;
  84690. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  84691. return _this;
  84692. }
  84693. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  84694. return "AnaglyphArcRotateCamera";
  84695. };
  84696. return AnaglyphArcRotateCamera;
  84697. }(BABYLON.ArcRotateCamera));
  84698. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  84699. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  84700. __extends(AnaglyphGamepadCamera, _super);
  84701. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  84702. var _this = _super.call(this, name, position, scene) || this;
  84703. _this.interaxialDistance = interaxialDistance;
  84704. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  84705. return _this;
  84706. }
  84707. AnaglyphGamepadCamera.prototype.getClassName = function () {
  84708. return "AnaglyphGamepadCamera";
  84709. };
  84710. return AnaglyphGamepadCamera;
  84711. }(BABYLON.GamepadCamera));
  84712. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  84713. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  84714. __extends(AnaglyphUniversalCamera, _super);
  84715. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  84716. var _this = _super.call(this, name, position, scene) || this;
  84717. _this.interaxialDistance = interaxialDistance;
  84718. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  84719. return _this;
  84720. }
  84721. AnaglyphUniversalCamera.prototype.getClassName = function () {
  84722. return "AnaglyphUniversalCamera";
  84723. };
  84724. return AnaglyphUniversalCamera;
  84725. }(BABYLON.UniversalCamera));
  84726. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  84727. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  84728. __extends(StereoscopicFreeCamera, _super);
  84729. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  84730. var _this = _super.call(this, name, position, scene) || this;
  84731. _this.interaxialDistance = interaxialDistance;
  84732. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  84733. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  84734. return _this;
  84735. }
  84736. StereoscopicFreeCamera.prototype.getClassName = function () {
  84737. return "StereoscopicFreeCamera";
  84738. };
  84739. return StereoscopicFreeCamera;
  84740. }(BABYLON.FreeCamera));
  84741. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  84742. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  84743. __extends(StereoscopicArcRotateCamera, _super);
  84744. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  84745. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  84746. _this.interaxialDistance = interaxialDistance;
  84747. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  84748. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  84749. return _this;
  84750. }
  84751. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  84752. return "StereoscopicArcRotateCamera";
  84753. };
  84754. return StereoscopicArcRotateCamera;
  84755. }(BABYLON.ArcRotateCamera));
  84756. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  84757. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  84758. __extends(StereoscopicGamepadCamera, _super);
  84759. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  84760. var _this = _super.call(this, name, position, scene) || this;
  84761. _this.interaxialDistance = interaxialDistance;
  84762. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  84763. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  84764. return _this;
  84765. }
  84766. StereoscopicGamepadCamera.prototype.getClassName = function () {
  84767. return "StereoscopicGamepadCamera";
  84768. };
  84769. return StereoscopicGamepadCamera;
  84770. }(BABYLON.GamepadCamera));
  84771. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  84772. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  84773. __extends(StereoscopicUniversalCamera, _super);
  84774. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  84775. var _this = _super.call(this, name, position, scene) || this;
  84776. _this.interaxialDistance = interaxialDistance;
  84777. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  84778. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  84779. return _this;
  84780. }
  84781. StereoscopicUniversalCamera.prototype.getClassName = function () {
  84782. return "StereoscopicUniversalCamera";
  84783. };
  84784. return StereoscopicUniversalCamera;
  84785. }(BABYLON.UniversalCamera));
  84786. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  84787. })(BABYLON || (BABYLON = {}));
  84788. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  84789. "use strict";
  84790. var BABYLON;
  84791. (function (BABYLON) {
  84792. var VRExperienceHelperGazer = /** @class */ (function () {
  84793. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  84794. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  84795. this.scene = scene;
  84796. this._pointerDownOnMeshAsked = false;
  84797. this._isActionableMesh = false;
  84798. this._teleportationRequestInitiated = false;
  84799. this._teleportationBackRequestInitiated = false;
  84800. this._dpadPressed = true;
  84801. this._activePointer = false;
  84802. this._id = VRExperienceHelperGazer._idCounter++;
  84803. // Gaze tracker
  84804. if (!gazeTrackerToClone) {
  84805. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  84806. this._gazeTracker.bakeCurrentTransformIntoVertices();
  84807. this._gazeTracker.isPickable = false;
  84808. this._gazeTracker.isVisible = false;
  84809. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  84810. targetMat.specularColor = BABYLON.Color3.Black();
  84811. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  84812. targetMat.backFaceCulling = false;
  84813. this._gazeTracker.material = targetMat;
  84814. }
  84815. else {
  84816. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  84817. }
  84818. }
  84819. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  84820. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  84821. };
  84822. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  84823. this._pointerDownOnMeshAsked = true;
  84824. if (this._currentMeshSelected && this._currentHit) {
  84825. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  84826. }
  84827. };
  84828. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  84829. if (this._currentMeshSelected && this._currentHit) {
  84830. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  84831. }
  84832. this._pointerDownOnMeshAsked = false;
  84833. };
  84834. VRExperienceHelperGazer.prototype._activatePointer = function () {
  84835. this._activePointer = true;
  84836. };
  84837. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  84838. this._activePointer = false;
  84839. };
  84840. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  84841. };
  84842. VRExperienceHelperGazer.prototype.dispose = function () {
  84843. this._interactionsEnabled = false;
  84844. this._teleportationEnabled = false;
  84845. };
  84846. VRExperienceHelperGazer._idCounter = 0;
  84847. return VRExperienceHelperGazer;
  84848. }());
  84849. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  84850. __extends(VRExperienceHelperControllerGazer, _super);
  84851. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  84852. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  84853. _this.webVRController = webVRController;
  84854. // Laser pointer
  84855. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  84856. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  84857. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  84858. laserPointerMaterial.alpha = 0.6;
  84859. _this._laserPointer.material = laserPointerMaterial;
  84860. _this._laserPointer.rotation.x = Math.PI / 2;
  84861. _this._laserPointer.position.z = -0.5;
  84862. _this._laserPointer.isVisible = false;
  84863. if (!webVRController.mesh) {
  84864. // Create an empty mesh that is used prior to loading the high quality model
  84865. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  84866. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  84867. preloadPointerPose.rotation.x = -0.7;
  84868. preloadMesh.addChild(preloadPointerPose);
  84869. webVRController.attachToMesh(preloadMesh);
  84870. }
  84871. _this._setLaserPointerParent(webVRController.mesh);
  84872. return _this;
  84873. }
  84874. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  84875. return this.webVRController.getForwardRay(length);
  84876. };
  84877. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  84878. _super.prototype._activatePointer.call(this);
  84879. this._laserPointer.isVisible = true;
  84880. };
  84881. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  84882. _super.prototype._deactivatePointer.call(this);
  84883. this._laserPointer.isVisible = false;
  84884. };
  84885. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  84886. this._laserPointer.material.emissiveColor = color;
  84887. };
  84888. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  84889. var makeNotPick = function (root) {
  84890. root.name += " laserPointer";
  84891. root.getChildMeshes().forEach(function (c) {
  84892. makeNotPick(c);
  84893. });
  84894. };
  84895. makeNotPick(mesh);
  84896. var childMeshes = mesh.getChildMeshes();
  84897. this.webVRController._pointingPoseNode = null;
  84898. for (var i = 0; i < childMeshes.length; i++) {
  84899. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  84900. mesh = childMeshes[i];
  84901. this.webVRController._pointingPoseNode = mesh;
  84902. break;
  84903. }
  84904. }
  84905. this._laserPointer.parent = mesh;
  84906. };
  84907. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  84908. this._laserPointer.scaling.y = distance;
  84909. this._laserPointer.position.z = -distance / 2;
  84910. };
  84911. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  84912. _super.prototype.dispose.call(this);
  84913. this._laserPointer.dispose();
  84914. };
  84915. return VRExperienceHelperControllerGazer;
  84916. }(VRExperienceHelperGazer));
  84917. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  84918. __extends(VRExperienceHelperCameraGazer, _super);
  84919. function VRExperienceHelperCameraGazer(getCamera, scene) {
  84920. var _this = _super.call(this, scene) || this;
  84921. _this.getCamera = getCamera;
  84922. return _this;
  84923. }
  84924. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  84925. var camera = this.getCamera();
  84926. if (camera) {
  84927. return camera.getForwardRay(length);
  84928. }
  84929. else {
  84930. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  84931. }
  84932. };
  84933. return VRExperienceHelperCameraGazer;
  84934. }(VRExperienceHelperGazer));
  84935. /**
  84936. * Helps to quickly add VR support to an existing scene.
  84937. * See http://doc.babylonjs.com/how_to/webvr_helper
  84938. */
  84939. var VRExperienceHelper = /** @class */ (function () {
  84940. /**
  84941. * Instantiates a VRExperienceHelper.
  84942. * Helps to quickly add VR support to an existing scene.
  84943. * @param scene The scene the VRExperienceHelper belongs to.
  84944. * @param webVROptions Options to modify the vr experience helper's behavior.
  84945. */
  84946. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  84947. if (webVROptions === void 0) { webVROptions = {}; }
  84948. var _this = this;
  84949. this.webVROptions = webVROptions;
  84950. // Can the system support WebVR, even if a headset isn't plugged in?
  84951. this._webVRsupported = false;
  84952. // If WebVR is supported, is a headset plugged in and are we ready to present?
  84953. this._webVRready = false;
  84954. // Are we waiting for the requestPresent callback to complete?
  84955. this._webVRrequesting = false;
  84956. // Are we presenting to the headset right now?
  84957. this._webVRpresenting = false;
  84958. // Are we presenting in the fullscreen fallback?
  84959. this._fullscreenVRpresenting = false;
  84960. /**
  84961. * Observable raised when entering VR.
  84962. */
  84963. this.onEnteringVRObservable = new BABYLON.Observable();
  84964. /**
  84965. * Observable raised when exiting VR.
  84966. */
  84967. this.onExitingVRObservable = new BABYLON.Observable();
  84968. /**
  84969. * Observable raised when controller mesh is loaded.
  84970. */
  84971. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  84972. this._useCustomVRButton = false;
  84973. this._teleportationRequested = false;
  84974. this._teleportActive = false;
  84975. this._floorMeshesCollection = [];
  84976. this._rotationAllowed = true;
  84977. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  84978. this._rotationRightAsked = false;
  84979. this._rotationLeftAsked = false;
  84980. this._isDefaultTeleportationTarget = true;
  84981. this._teleportationFillColor = "#444444";
  84982. this._teleportationBorderColor = "#FFFFFF";
  84983. this._rotationAngle = 0;
  84984. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  84985. this._padSensibilityUp = 0.65;
  84986. this._padSensibilityDown = 0.35;
  84987. this.leftController = null;
  84988. this.rightController = null;
  84989. /**
  84990. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  84991. */
  84992. this.onNewMeshSelected = new BABYLON.Observable();
  84993. /**
  84994. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  84995. */
  84996. this.onNewMeshPicked = new BABYLON.Observable();
  84997. /**
  84998. * Observable raised before camera teleportation
  84999. */
  85000. this.onBeforeCameraTeleport = new BABYLON.Observable();
  85001. /**
  85002. * Observable raised after camera teleportation
  85003. */
  85004. this.onAfterCameraTeleport = new BABYLON.Observable();
  85005. /**
  85006. * Observable raised when current selected mesh gets unselected
  85007. */
  85008. this.onSelectedMeshUnselected = new BABYLON.Observable();
  85009. /**
  85010. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  85011. */
  85012. this.teleportationEnabled = true;
  85013. this._teleportationInitialized = false;
  85014. this._interactionsEnabled = false;
  85015. this._interactionsRequested = false;
  85016. this._displayGaze = true;
  85017. this._displayLaserPointer = true;
  85018. this._onResize = function () {
  85019. _this.moveButtonToBottomRight();
  85020. if (_this._fullscreenVRpresenting && _this._webVRready) {
  85021. _this.exitVR();
  85022. }
  85023. };
  85024. this._onFullscreenChange = function () {
  85025. if (document.fullscreen !== undefined) {
  85026. _this._fullscreenVRpresenting = document.fullscreen;
  85027. }
  85028. else if (document.mozFullScreen !== undefined) {
  85029. _this._fullscreenVRpresenting = document.mozFullScreen;
  85030. }
  85031. else if (document.webkitIsFullScreen !== undefined) {
  85032. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  85033. }
  85034. else if (document.msIsFullScreen !== undefined) {
  85035. _this._fullscreenVRpresenting = document.msIsFullScreen;
  85036. }
  85037. if (!_this._fullscreenVRpresenting && _this._canvas) {
  85038. _this.exitVR();
  85039. if (!_this._useCustomVRButton) {
  85040. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  85041. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  85042. }
  85043. }
  85044. };
  85045. this.beforeRender = function () {
  85046. if (_this.leftController && _this.leftController._activePointer) {
  85047. _this._castRayAndSelectObject(_this.leftController);
  85048. }
  85049. if (_this.rightController && _this.rightController._activePointer) {
  85050. _this._castRayAndSelectObject(_this.rightController);
  85051. }
  85052. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  85053. _this._castRayAndSelectObject(_this._cameraGazer);
  85054. }
  85055. else {
  85056. _this._cameraGazer._gazeTracker.isVisible = false;
  85057. }
  85058. };
  85059. this._onNewGamepadConnected = function (gamepad) {
  85060. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  85061. if (gamepad.leftStick) {
  85062. gamepad.onleftstickchanged(function (stickValues) {
  85063. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  85064. // Listening to classic/xbox gamepad only if no VR controller is active
  85065. if ((!_this.leftController && !_this.rightController) ||
  85066. ((_this.leftController && !_this.leftController._activePointer) &&
  85067. (_this.rightController && !_this.rightController._activePointer))) {
  85068. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  85069. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  85070. }
  85071. }
  85072. });
  85073. }
  85074. if (gamepad.rightStick) {
  85075. gamepad.onrightstickchanged(function (stickValues) {
  85076. if (_this._teleportationInitialized) {
  85077. _this._checkRotate(stickValues, _this._cameraGazer);
  85078. }
  85079. });
  85080. }
  85081. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  85082. gamepad.onbuttondown(function (buttonPressed) {
  85083. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  85084. _this._cameraGazer._selectionPointerDown();
  85085. }
  85086. });
  85087. gamepad.onbuttonup(function (buttonPressed) {
  85088. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  85089. _this._cameraGazer._selectionPointerUp();
  85090. }
  85091. });
  85092. }
  85093. }
  85094. else {
  85095. var webVRController = gamepad;
  85096. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  85097. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  85098. _this.rightController = controller;
  85099. }
  85100. else {
  85101. _this.leftController = controller;
  85102. }
  85103. _this._tryEnableInteractionOnController(controller);
  85104. }
  85105. };
  85106. // 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
  85107. this._tryEnableInteractionOnController = function (controller) {
  85108. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  85109. _this._enableInteractionOnController(controller);
  85110. }
  85111. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  85112. _this._enableTeleportationOnController(controller);
  85113. }
  85114. };
  85115. this._onNewGamepadDisconnected = function (gamepad) {
  85116. if (gamepad instanceof BABYLON.WebVRController) {
  85117. if (gamepad.hand === "left" && _this.leftController != null) {
  85118. _this.leftController.dispose();
  85119. _this.leftController = null;
  85120. }
  85121. if (gamepad.hand === "right" && _this.rightController != null) {
  85122. _this.rightController.dispose();
  85123. _this.rightController = null;
  85124. }
  85125. }
  85126. };
  85127. this._workingVector = BABYLON.Vector3.Zero();
  85128. this._workingQuaternion = BABYLON.Quaternion.Identity();
  85129. this._workingMatrix = BABYLON.Matrix.Identity();
  85130. this._scene = scene;
  85131. this._canvas = scene.getEngine().getRenderingCanvas();
  85132. // Parse options
  85133. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  85134. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  85135. }
  85136. if (webVROptions.createDeviceOrientationCamera === undefined) {
  85137. webVROptions.createDeviceOrientationCamera = true;
  85138. }
  85139. if (webVROptions.defaultHeight === undefined) {
  85140. webVROptions.defaultHeight = 1.7;
  85141. }
  85142. if (webVROptions.useCustomVRButton) {
  85143. this._useCustomVRButton = true;
  85144. if (webVROptions.customVRButton) {
  85145. this._btnVR = webVROptions.customVRButton;
  85146. }
  85147. }
  85148. if (webVROptions.rayLength) {
  85149. this._rayLength = webVROptions.rayLength;
  85150. }
  85151. this._defaultHeight = webVROptions.defaultHeight;
  85152. if (webVROptions.positionScale) {
  85153. this._rayLength *= webVROptions.positionScale;
  85154. this._defaultHeight *= webVROptions.positionScale;
  85155. }
  85156. // Set position
  85157. if (this._scene.activeCamera) {
  85158. this._position = this._scene.activeCamera.position.clone();
  85159. }
  85160. else {
  85161. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  85162. }
  85163. // Set non-vr camera
  85164. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  85165. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  85166. // Copy data from existing camera
  85167. if (this._scene.activeCamera) {
  85168. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  85169. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  85170. // Set rotation from previous camera
  85171. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  85172. var targetCamera = this._scene.activeCamera;
  85173. if (targetCamera.rotationQuaternion) {
  85174. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  85175. }
  85176. else {
  85177. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  85178. }
  85179. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  85180. }
  85181. }
  85182. this._scene.activeCamera = this._deviceOrientationCamera;
  85183. if (this._canvas) {
  85184. this._scene.activeCamera.attachControl(this._canvas);
  85185. }
  85186. }
  85187. else {
  85188. this._existingCamera = this._scene.activeCamera;
  85189. }
  85190. // Create VR cameras
  85191. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  85192. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  85193. }
  85194. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  85195. this._webVRCamera.useStandingMatrix();
  85196. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  85197. // Create default button
  85198. if (!this._useCustomVRButton) {
  85199. this._btnVR = document.createElement("BUTTON");
  85200. this._btnVR.className = "babylonVRicon";
  85201. this._btnVR.id = "babylonVRiconbtn";
  85202. this._btnVR.title = "Click to switch to VR";
  85203. 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) }";
  85204. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  85205. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  85206. // css += ".babylonVRicon.vrdisplaysupported { }";
  85207. // css += ".babylonVRicon.vrdisplayready { }";
  85208. // css += ".babylonVRicon.vrdisplayrequesting { }";
  85209. var style = document.createElement('style');
  85210. style.appendChild(document.createTextNode(css));
  85211. document.getElementsByTagName('head')[0].appendChild(style);
  85212. this.moveButtonToBottomRight();
  85213. }
  85214. // VR button click event
  85215. if (this._btnVR) {
  85216. this._btnVR.addEventListener("click", function () {
  85217. if (!_this.isInVRMode) {
  85218. _this.enterVR();
  85219. }
  85220. else {
  85221. _this.exitVR();
  85222. }
  85223. });
  85224. }
  85225. // Window events
  85226. window.addEventListener("resize", this._onResize);
  85227. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  85228. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  85229. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  85230. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  85231. // Display vr button when headset is connected
  85232. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  85233. this.displayVRButton();
  85234. }
  85235. else {
  85236. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  85237. if (e.vrDisplay) {
  85238. _this.displayVRButton();
  85239. }
  85240. });
  85241. }
  85242. // Exiting VR mode using 'ESC' key on desktop
  85243. this._onKeyDown = function (event) {
  85244. if (event.keyCode === 27 && _this.isInVRMode) {
  85245. _this.exitVR();
  85246. }
  85247. };
  85248. document.addEventListener("keydown", this._onKeyDown);
  85249. // Exiting VR mode double tapping the touch screen
  85250. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  85251. if (_this.isInVRMode) {
  85252. _this.exitVR();
  85253. if (_this._fullscreenVRpresenting) {
  85254. _this._scene.getEngine().switchFullscreen(true);
  85255. }
  85256. }
  85257. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  85258. // Listen for WebVR display changes
  85259. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  85260. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  85261. this._onVRRequestPresentStart = function () {
  85262. _this._webVRrequesting = true;
  85263. _this.updateButtonVisibility();
  85264. };
  85265. this._onVRRequestPresentComplete = function (success) {
  85266. _this._webVRrequesting = false;
  85267. _this.updateButtonVisibility();
  85268. };
  85269. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  85270. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  85271. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  85272. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  85273. scene.onDisposeObservable.add(function () {
  85274. _this.dispose();
  85275. });
  85276. // Gamepad connection events
  85277. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  85278. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  85279. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  85280. this.updateButtonVisibility();
  85281. //create easing functions
  85282. this._circleEase = new BABYLON.CircleEase();
  85283. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  85284. }
  85285. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  85286. /** Return this.onEnteringVRObservable
  85287. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  85288. */
  85289. get: function () {
  85290. return this.onEnteringVRObservable;
  85291. },
  85292. enumerable: true,
  85293. configurable: true
  85294. });
  85295. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  85296. /** Return this.onExitingVRObservable
  85297. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  85298. */
  85299. get: function () {
  85300. return this.onExitingVRObservable;
  85301. },
  85302. enumerable: true,
  85303. configurable: true
  85304. });
  85305. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  85306. /** Return this.onControllerMeshLoadedObservable
  85307. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  85308. */
  85309. get: function () {
  85310. return this.onControllerMeshLoadedObservable;
  85311. },
  85312. enumerable: true,
  85313. configurable: true
  85314. });
  85315. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  85316. /**
  85317. * The mesh used to display where the user is going to teleport.
  85318. */
  85319. get: function () {
  85320. return this._teleportationTarget;
  85321. },
  85322. /**
  85323. * Sets the mesh to be used to display where the user is going to teleport.
  85324. */
  85325. set: function (value) {
  85326. if (value) {
  85327. value.name = "teleportationTarget";
  85328. this._isDefaultTeleportationTarget = false;
  85329. this._teleportationTarget = value;
  85330. }
  85331. },
  85332. enumerable: true,
  85333. configurable: true
  85334. });
  85335. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  85336. /**
  85337. * The mesh used to display where the user is selecting,
  85338. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  85339. * See http://doc.babylonjs.com/resources/baking_transformations
  85340. */
  85341. get: function () {
  85342. return this._cameraGazer._gazeTracker;
  85343. },
  85344. set: function (value) {
  85345. if (value) {
  85346. this._cameraGazer._gazeTracker = value;
  85347. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  85348. this._cameraGazer._gazeTracker.isPickable = false;
  85349. this._cameraGazer._gazeTracker.isVisible = false;
  85350. this._cameraGazer._gazeTracker.name = "gazeTracker";
  85351. if (this.leftController) {
  85352. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  85353. }
  85354. if (this.rightController) {
  85355. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  85356. }
  85357. }
  85358. },
  85359. enumerable: true,
  85360. configurable: true
  85361. });
  85362. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  85363. /**
  85364. * If the ray of the gaze should be displayed.
  85365. */
  85366. get: function () {
  85367. return this._displayGaze;
  85368. },
  85369. /**
  85370. * Sets if the ray of the gaze should be displayed.
  85371. */
  85372. set: function (value) {
  85373. this._displayGaze = value;
  85374. if (!value) {
  85375. this._cameraGazer._gazeTracker.isVisible = false;
  85376. if (this.leftController) {
  85377. this.leftController._gazeTracker.isVisible = false;
  85378. }
  85379. if (this.rightController) {
  85380. this.rightController._gazeTracker.isVisible = false;
  85381. }
  85382. }
  85383. },
  85384. enumerable: true,
  85385. configurable: true
  85386. });
  85387. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  85388. /**
  85389. * If the ray of the LaserPointer should be displayed.
  85390. */
  85391. get: function () {
  85392. return this._displayLaserPointer;
  85393. },
  85394. /**
  85395. * Sets if the ray of the LaserPointer should be displayed.
  85396. */
  85397. set: function (value) {
  85398. this._displayLaserPointer = value;
  85399. if (!value) {
  85400. if (this.rightController) {
  85401. this.rightController._deactivatePointer();
  85402. this.rightController._gazeTracker.isVisible = false;
  85403. }
  85404. if (this.leftController) {
  85405. this.leftController._deactivatePointer();
  85406. this.leftController._gazeTracker.isVisible = false;
  85407. }
  85408. }
  85409. else {
  85410. if (this.rightController) {
  85411. this.rightController._activatePointer();
  85412. }
  85413. else if (this.leftController) {
  85414. this.leftController._activatePointer();
  85415. }
  85416. }
  85417. },
  85418. enumerable: true,
  85419. configurable: true
  85420. });
  85421. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  85422. /**
  85423. * The deviceOrientationCamera used as the camera when not in VR.
  85424. */
  85425. get: function () {
  85426. return this._deviceOrientationCamera;
  85427. },
  85428. enumerable: true,
  85429. configurable: true
  85430. });
  85431. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  85432. /**
  85433. * Based on the current WebVR support, returns the current VR camera used.
  85434. */
  85435. get: function () {
  85436. if (this._webVRready) {
  85437. return this._webVRCamera;
  85438. }
  85439. else {
  85440. return this._scene.activeCamera;
  85441. }
  85442. },
  85443. enumerable: true,
  85444. configurable: true
  85445. });
  85446. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  85447. /**
  85448. * The webVRCamera which is used when in VR.
  85449. */
  85450. get: function () {
  85451. return this._webVRCamera;
  85452. },
  85453. enumerable: true,
  85454. configurable: true
  85455. });
  85456. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  85457. /**
  85458. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  85459. */
  85460. get: function () {
  85461. return this._vrDeviceOrientationCamera;
  85462. },
  85463. enumerable: true,
  85464. configurable: true
  85465. });
  85466. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  85467. get: function () {
  85468. var result = this._cameraGazer._teleportationRequestInitiated
  85469. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  85470. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  85471. return result;
  85472. },
  85473. enumerable: true,
  85474. configurable: true
  85475. });
  85476. // Raised when one of the controller has loaded successfully its associated default mesh
  85477. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  85478. if (this.leftController && this.leftController.webVRController == webVRController) {
  85479. if (webVRController.mesh) {
  85480. this.leftController._setLaserPointerParent(webVRController.mesh);
  85481. }
  85482. }
  85483. if (this.rightController && this.rightController.webVRController == webVRController) {
  85484. if (webVRController.mesh) {
  85485. this.rightController._setLaserPointerParent(webVRController.mesh);
  85486. }
  85487. }
  85488. try {
  85489. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  85490. }
  85491. catch (err) {
  85492. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  85493. }
  85494. };
  85495. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  85496. /**
  85497. * Gets a value indicating if we are currently in VR mode.
  85498. */
  85499. get: function () {
  85500. return this._webVRpresenting || this._fullscreenVRpresenting;
  85501. },
  85502. enumerable: true,
  85503. configurable: true
  85504. });
  85505. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  85506. var vrDisplay = this._scene.getEngine().getVRDevice();
  85507. if (vrDisplay) {
  85508. var wasPresenting = this._webVRpresenting;
  85509. // A VR display is connected
  85510. this._webVRpresenting = vrDisplay.isPresenting;
  85511. if (wasPresenting && !this._webVRpresenting)
  85512. this.exitVR();
  85513. }
  85514. else {
  85515. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  85516. }
  85517. this.updateButtonVisibility();
  85518. };
  85519. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  85520. this._webVRsupported = eventArgs.vrSupported;
  85521. this._webVRready = !!eventArgs.vrDisplay;
  85522. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  85523. this.updateButtonVisibility();
  85524. };
  85525. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  85526. if (this._canvas && !this._useCustomVRButton) {
  85527. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  85528. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  85529. }
  85530. };
  85531. VRExperienceHelper.prototype.displayVRButton = function () {
  85532. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  85533. document.body.appendChild(this._btnVR);
  85534. this._btnVRDisplayed = true;
  85535. }
  85536. };
  85537. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  85538. if (!this._btnVR || this._useCustomVRButton) {
  85539. return;
  85540. }
  85541. this._btnVR.className = "babylonVRicon";
  85542. if (this.isInVRMode) {
  85543. this._btnVR.className += " vrdisplaypresenting";
  85544. }
  85545. else {
  85546. if (this._webVRready)
  85547. this._btnVR.className += " vrdisplayready";
  85548. if (this._webVRsupported)
  85549. this._btnVR.className += " vrdisplaysupported";
  85550. if (this._webVRrequesting)
  85551. this._btnVR.className += " vrdisplayrequesting";
  85552. }
  85553. };
  85554. /**
  85555. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  85556. * Otherwise, will use the fullscreen API.
  85557. */
  85558. VRExperienceHelper.prototype.enterVR = function () {
  85559. if (this.onEnteringVRObservable) {
  85560. try {
  85561. this.onEnteringVRObservable.notifyObservers(this);
  85562. }
  85563. catch (err) {
  85564. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  85565. }
  85566. }
  85567. if (this._scene.activeCamera) {
  85568. this._position = this._scene.activeCamera.position.clone();
  85569. // make sure that we return to the last active camera
  85570. this._existingCamera = this._scene.activeCamera;
  85571. }
  85572. if (this._webVRrequesting)
  85573. return;
  85574. // If WebVR is supported and a headset is connected
  85575. if (this._webVRready) {
  85576. if (!this._webVRpresenting) {
  85577. this._webVRCamera.position = this._position;
  85578. this._scene.activeCamera = this._webVRCamera;
  85579. }
  85580. }
  85581. else if (this._vrDeviceOrientationCamera) {
  85582. this._vrDeviceOrientationCamera.position = this._position;
  85583. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  85584. this._scene.getEngine().switchFullscreen(true);
  85585. this.updateButtonVisibility();
  85586. }
  85587. if (this._scene.activeCamera && this._canvas) {
  85588. this._scene.activeCamera.attachControl(this._canvas);
  85589. }
  85590. if (this._interactionsEnabled) {
  85591. this._scene.registerBeforeRender(this.beforeRender);
  85592. }
  85593. };
  85594. /**
  85595. * Attempt to exit VR, or fullscreen.
  85596. */
  85597. VRExperienceHelper.prototype.exitVR = function () {
  85598. if (this.onExitingVRObservable) {
  85599. try {
  85600. this.onExitingVRObservable.notifyObservers(this);
  85601. }
  85602. catch (err) {
  85603. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  85604. }
  85605. }
  85606. if (this._webVRpresenting) {
  85607. this._scene.getEngine().disableVR();
  85608. }
  85609. if (this._scene.activeCamera) {
  85610. this._position = this._scene.activeCamera.position.clone();
  85611. }
  85612. if (this._deviceOrientationCamera) {
  85613. this._deviceOrientationCamera.position = this._position;
  85614. this._scene.activeCamera = this._deviceOrientationCamera;
  85615. if (this._canvas) {
  85616. this._scene.activeCamera.attachControl(this._canvas);
  85617. }
  85618. }
  85619. else if (this._existingCamera) {
  85620. this._existingCamera.position = this._position;
  85621. this._scene.activeCamera = this._existingCamera;
  85622. }
  85623. this.updateButtonVisibility();
  85624. if (this._interactionsEnabled) {
  85625. this._scene.unregisterBeforeRender(this.beforeRender);
  85626. }
  85627. };
  85628. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  85629. /**
  85630. * The position of the vr experience helper.
  85631. */
  85632. get: function () {
  85633. return this._position;
  85634. },
  85635. /**
  85636. * Sets the position of the vr experience helper.
  85637. */
  85638. set: function (value) {
  85639. this._position = value;
  85640. if (this._scene.activeCamera) {
  85641. this._scene.activeCamera.position = value;
  85642. }
  85643. },
  85644. enumerable: true,
  85645. configurable: true
  85646. });
  85647. /**
  85648. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  85649. */
  85650. VRExperienceHelper.prototype.enableInteractions = function () {
  85651. var _this = this;
  85652. if (!this._interactionsEnabled) {
  85653. this._interactionsRequested = true;
  85654. if (this.leftController) {
  85655. this._enableInteractionOnController(this.leftController);
  85656. }
  85657. if (this.rightController) {
  85658. this._enableInteractionOnController(this.rightController);
  85659. }
  85660. this.raySelectionPredicate = function (mesh) {
  85661. return mesh.isVisible;
  85662. };
  85663. this.meshSelectionPredicate = function (mesh) {
  85664. return true;
  85665. };
  85666. this._raySelectionPredicate = function (mesh) {
  85667. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  85668. && mesh.name.indexOf("teleportationTarget") === -1
  85669. && mesh.name.indexOf("torusTeleportation") === -1
  85670. && mesh.name.indexOf("laserPointer") === -1)) {
  85671. return _this.raySelectionPredicate(mesh);
  85672. }
  85673. return false;
  85674. };
  85675. this._interactionsEnabled = true;
  85676. }
  85677. };
  85678. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  85679. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  85680. if (this._floorMeshesCollection[i].id === mesh.id) {
  85681. return true;
  85682. }
  85683. }
  85684. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  85685. return true;
  85686. }
  85687. return false;
  85688. };
  85689. /**
  85690. * Adds a floor mesh to be used for teleportation.
  85691. * @param floorMesh the mesh to be used for teleportation.
  85692. */
  85693. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  85694. if (!this._floorMeshesCollection) {
  85695. return;
  85696. }
  85697. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  85698. return;
  85699. }
  85700. this._floorMeshesCollection.push(floorMesh);
  85701. };
  85702. /**
  85703. * Removes a floor mesh from being used for teleportation.
  85704. * @param floorMesh the mesh to be removed.
  85705. */
  85706. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  85707. if (!this._floorMeshesCollection) {
  85708. return;
  85709. }
  85710. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  85711. if (meshIndex !== -1) {
  85712. this._floorMeshesCollection.splice(meshIndex, 1);
  85713. }
  85714. };
  85715. /**
  85716. * Enables interactions and teleportation using the VR controllers and gaze.
  85717. * @param vrTeleportationOptions options to modify teleportation behavior.
  85718. */
  85719. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  85720. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  85721. if (!this._teleportationInitialized) {
  85722. this._teleportationRequested = true;
  85723. this.enableInteractions();
  85724. if (vrTeleportationOptions.floorMeshName) {
  85725. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  85726. }
  85727. if (vrTeleportationOptions.floorMeshes) {
  85728. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  85729. }
  85730. if (this.leftController != null) {
  85731. this._enableTeleportationOnController(this.leftController);
  85732. }
  85733. if (this.rightController != null) {
  85734. this._enableTeleportationOnController(this.rightController);
  85735. }
  85736. // Creates an image processing post process for the vignette not relying
  85737. // on the main scene configuration for image processing to reduce setup and spaces
  85738. // (gamma/linear) conflicts.
  85739. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  85740. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  85741. imageProcessingConfiguration.vignetteEnabled = true;
  85742. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  85743. this._webVRCamera.detachPostProcess(this._postProcessMove);
  85744. this._teleportationInitialized = true;
  85745. if (this._isDefaultTeleportationTarget) {
  85746. this._createTeleportationCircles();
  85747. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  85748. }
  85749. }
  85750. };
  85751. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  85752. var _this = this;
  85753. var controllerMesh = controller.webVRController.mesh;
  85754. if (controllerMesh) {
  85755. controller._interactionsEnabled = true;
  85756. controller._activatePointer();
  85757. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  85758. // Enabling / disabling laserPointer
  85759. if (_this._displayLaserPointer && stateObject.value === 1) {
  85760. if (controller._activePointer) {
  85761. controller._deactivatePointer();
  85762. }
  85763. else {
  85764. controller._activatePointer();
  85765. }
  85766. if (_this.displayGaze) {
  85767. controller._gazeTracker.isVisible = controller._activePointer;
  85768. }
  85769. }
  85770. });
  85771. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  85772. if (!controller._pointerDownOnMeshAsked) {
  85773. if (stateObject.value > _this._padSensibilityUp) {
  85774. controller._selectionPointerDown();
  85775. }
  85776. }
  85777. else if (stateObject.value < _this._padSensibilityDown) {
  85778. controller._selectionPointerUp();
  85779. }
  85780. });
  85781. }
  85782. };
  85783. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  85784. // Dont teleport if another gaze already requested teleportation
  85785. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  85786. return;
  85787. }
  85788. if (!gazer._teleportationRequestInitiated) {
  85789. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  85790. gazer._activatePointer();
  85791. gazer._teleportationRequestInitiated = true;
  85792. }
  85793. }
  85794. else {
  85795. // Listening to the proper controller values changes to confirm teleportation
  85796. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  85797. if (this._teleportActive) {
  85798. this._teleportCamera(this._haloCenter);
  85799. }
  85800. gazer._teleportationRequestInitiated = false;
  85801. }
  85802. }
  85803. };
  85804. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  85805. // Only rotate when user is not currently selecting a teleportation location
  85806. if (gazer._teleportationRequestInitiated) {
  85807. return;
  85808. }
  85809. if (!this._rotationLeftAsked) {
  85810. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  85811. this._rotationLeftAsked = true;
  85812. if (this._rotationAllowed) {
  85813. this._rotateCamera(false);
  85814. }
  85815. }
  85816. }
  85817. else {
  85818. if (stateObject.x > -this._padSensibilityDown) {
  85819. this._rotationLeftAsked = false;
  85820. }
  85821. }
  85822. if (!this._rotationRightAsked) {
  85823. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  85824. this._rotationRightAsked = true;
  85825. if (this._rotationAllowed) {
  85826. this._rotateCamera(true);
  85827. }
  85828. }
  85829. }
  85830. else {
  85831. if (stateObject.x < this._padSensibilityDown) {
  85832. this._rotationRightAsked = false;
  85833. }
  85834. }
  85835. };
  85836. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  85837. // Only teleport backwards when user is not currently selecting a teleportation location
  85838. if (gazer._teleportationRequestInitiated) {
  85839. return;
  85840. }
  85841. // Teleport backwards
  85842. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  85843. if (!gazer._teleportationBackRequestInitiated) {
  85844. if (!this.currentVRCamera) {
  85845. return;
  85846. }
  85847. // Get rotation and position of the current camera
  85848. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  85849. var position = this.currentVRCamera.position;
  85850. // If the camera has device position, use that instead
  85851. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  85852. rotation = this.currentVRCamera.deviceRotationQuaternion;
  85853. position = this.currentVRCamera.devicePosition;
  85854. }
  85855. // Get matrix with only the y rotation of the device rotation
  85856. rotation.toEulerAnglesToRef(this._workingVector);
  85857. this._workingVector.z = 0;
  85858. this._workingVector.x = 0;
  85859. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  85860. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  85861. // Rotate backwards ray by device rotation to cast at the ground behind the user
  85862. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  85863. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  85864. var ray = new BABYLON.Ray(position, this._workingVector);
  85865. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  85866. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  85867. this._teleportCamera(hit.pickedPoint);
  85868. }
  85869. gazer._teleportationBackRequestInitiated = true;
  85870. }
  85871. }
  85872. else {
  85873. gazer._teleportationBackRequestInitiated = false;
  85874. }
  85875. };
  85876. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  85877. var _this = this;
  85878. var controllerMesh = controller.webVRController.mesh;
  85879. if (controllerMesh) {
  85880. if (!controller._interactionsEnabled) {
  85881. this._enableInteractionOnController(controller);
  85882. }
  85883. controller._interactionsEnabled = true;
  85884. controller._teleportationEnabled = true;
  85885. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  85886. controller._dpadPressed = false;
  85887. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  85888. controller._dpadPressed = stateObject.pressed;
  85889. if (!controller._dpadPressed) {
  85890. _this._rotationLeftAsked = false;
  85891. _this._rotationRightAsked = false;
  85892. controller._teleportationBackRequestInitiated = false;
  85893. }
  85894. });
  85895. }
  85896. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  85897. if (_this.teleportationEnabled) {
  85898. _this._checkTeleportBackwards(stateObject, controller);
  85899. _this._checkTeleportWithRay(stateObject, controller);
  85900. }
  85901. _this._checkRotate(stateObject, controller);
  85902. });
  85903. }
  85904. };
  85905. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  85906. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  85907. this._teleportationTarget.isPickable = false;
  85908. var length = 512;
  85909. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  85910. dynamicTexture.hasAlpha = true;
  85911. var context = dynamicTexture.getContext();
  85912. var centerX = length / 2;
  85913. var centerY = length / 2;
  85914. var radius = 200;
  85915. context.beginPath();
  85916. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  85917. context.fillStyle = this._teleportationFillColor;
  85918. context.fill();
  85919. context.lineWidth = 10;
  85920. context.strokeStyle = this._teleportationBorderColor;
  85921. context.stroke();
  85922. context.closePath();
  85923. dynamicTexture.update();
  85924. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  85925. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  85926. this._teleportationTarget.material = teleportationCircleMaterial;
  85927. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  85928. torus.isPickable = false;
  85929. torus.parent = this._teleportationTarget;
  85930. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  85931. var keys = [];
  85932. keys.push({
  85933. frame: 0,
  85934. value: 0
  85935. });
  85936. keys.push({
  85937. frame: 30,
  85938. value: 0.4
  85939. });
  85940. keys.push({
  85941. frame: 60,
  85942. value: 0
  85943. });
  85944. animationInnerCircle.setKeys(keys);
  85945. var easingFunction = new BABYLON.SineEase();
  85946. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  85947. animationInnerCircle.setEasingFunction(easingFunction);
  85948. torus.animations = [];
  85949. torus.animations.push(animationInnerCircle);
  85950. this._scene.beginAnimation(torus, 0, 60, true);
  85951. this._hideTeleportationTarget();
  85952. };
  85953. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  85954. this._teleportActive = true;
  85955. if (this._teleportationInitialized) {
  85956. this._teleportationTarget.isVisible = true;
  85957. if (this._isDefaultTeleportationTarget) {
  85958. this._teleportationTarget.getChildren()[0].isVisible = true;
  85959. }
  85960. }
  85961. };
  85962. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  85963. this._teleportActive = false;
  85964. if (this._teleportationInitialized) {
  85965. this._teleportationTarget.isVisible = false;
  85966. if (this._isDefaultTeleportationTarget) {
  85967. this._teleportationTarget.getChildren()[0].isVisible = false;
  85968. }
  85969. }
  85970. };
  85971. VRExperienceHelper.prototype._rotateCamera = function (right) {
  85972. var _this = this;
  85973. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  85974. return;
  85975. }
  85976. if (right) {
  85977. this._rotationAngle++;
  85978. }
  85979. else {
  85980. this._rotationAngle--;
  85981. }
  85982. this.currentVRCamera.animations = [];
  85983. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  85984. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  85985. var animationRotationKeys = [];
  85986. animationRotationKeys.push({
  85987. frame: 0,
  85988. value: this.currentVRCamera.rotationQuaternion
  85989. });
  85990. animationRotationKeys.push({
  85991. frame: 6,
  85992. value: target
  85993. });
  85994. animationRotation.setKeys(animationRotationKeys);
  85995. animationRotation.setEasingFunction(this._circleEase);
  85996. this.currentVRCamera.animations.push(animationRotation);
  85997. this._postProcessMove.animations = [];
  85998. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  85999. var vignetteWeightKeys = [];
  86000. vignetteWeightKeys.push({
  86001. frame: 0,
  86002. value: 0
  86003. });
  86004. vignetteWeightKeys.push({
  86005. frame: 3,
  86006. value: 4
  86007. });
  86008. vignetteWeightKeys.push({
  86009. frame: 6,
  86010. value: 0
  86011. });
  86012. animationPP.setKeys(vignetteWeightKeys);
  86013. animationPP.setEasingFunction(this._circleEase);
  86014. this._postProcessMove.animations.push(animationPP);
  86015. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  86016. var vignetteStretchKeys = [];
  86017. vignetteStretchKeys.push({
  86018. frame: 0,
  86019. value: 0
  86020. });
  86021. vignetteStretchKeys.push({
  86022. frame: 3,
  86023. value: 10
  86024. });
  86025. vignetteStretchKeys.push({
  86026. frame: 6,
  86027. value: 0
  86028. });
  86029. animationPP2.setKeys(vignetteStretchKeys);
  86030. animationPP2.setEasingFunction(this._circleEase);
  86031. this._postProcessMove.animations.push(animationPP2);
  86032. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  86033. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  86034. this._postProcessMove.samples = 4;
  86035. this._webVRCamera.attachPostProcess(this._postProcessMove);
  86036. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  86037. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  86038. });
  86039. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  86040. };
  86041. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  86042. if (hit.pickedPoint) {
  86043. if (gazer._teleportationRequestInitiated) {
  86044. this._displayTeleportationTarget();
  86045. this._haloCenter.copyFrom(hit.pickedPoint);
  86046. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  86047. }
  86048. var pickNormal = hit.getNormal(true, false);
  86049. if (pickNormal) {
  86050. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  86051. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  86052. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  86053. }
  86054. this._teleportationTarget.position.y += 0.1;
  86055. }
  86056. };
  86057. VRExperienceHelper.prototype._teleportCamera = function (location) {
  86058. var _this = this;
  86059. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  86060. return;
  86061. }
  86062. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  86063. // offset of the headset from the anchor.
  86064. if (this.webVRCamera.leftCamera) {
  86065. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  86066. this._workingVector.subtractInPlace(this.webVRCamera.position);
  86067. location.subtractToRef(this._workingVector, this._workingVector);
  86068. }
  86069. else {
  86070. this._workingVector.copyFrom(location);
  86071. }
  86072. // Add height to account for user's height offset
  86073. if (this.isInVRMode) {
  86074. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  86075. }
  86076. else {
  86077. this._workingVector.y += this._defaultHeight;
  86078. }
  86079. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  86080. // Create animation from the camera's position to the new location
  86081. this.currentVRCamera.animations = [];
  86082. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  86083. var animationCameraTeleportationKeys = [{
  86084. frame: 0,
  86085. value: this.currentVRCamera.position
  86086. },
  86087. {
  86088. frame: 11,
  86089. value: this._workingVector
  86090. }
  86091. ];
  86092. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  86093. animationCameraTeleportation.setEasingFunction(this._circleEase);
  86094. this.currentVRCamera.animations.push(animationCameraTeleportation);
  86095. this._postProcessMove.animations = [];
  86096. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  86097. var vignetteWeightKeys = [];
  86098. vignetteWeightKeys.push({
  86099. frame: 0,
  86100. value: 0
  86101. });
  86102. vignetteWeightKeys.push({
  86103. frame: 5,
  86104. value: 8
  86105. });
  86106. vignetteWeightKeys.push({
  86107. frame: 11,
  86108. value: 0
  86109. });
  86110. animationPP.setKeys(vignetteWeightKeys);
  86111. this._postProcessMove.animations.push(animationPP);
  86112. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  86113. var vignetteStretchKeys = [];
  86114. vignetteStretchKeys.push({
  86115. frame: 0,
  86116. value: 0
  86117. });
  86118. vignetteStretchKeys.push({
  86119. frame: 5,
  86120. value: 10
  86121. });
  86122. vignetteStretchKeys.push({
  86123. frame: 11,
  86124. value: 0
  86125. });
  86126. animationPP2.setKeys(vignetteStretchKeys);
  86127. this._postProcessMove.animations.push(animationPP2);
  86128. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  86129. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  86130. this._webVRCamera.attachPostProcess(this._postProcessMove);
  86131. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  86132. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  86133. });
  86134. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  86135. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  86136. });
  86137. this._hideTeleportationTarget();
  86138. };
  86139. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  86140. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  86141. return;
  86142. }
  86143. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  86144. // Moving the gazeTracker on the mesh face targetted
  86145. if (hit && hit.pickedPoint) {
  86146. if (this._displayGaze) {
  86147. var multiplier = 1;
  86148. gazer._gazeTracker.isVisible = true;
  86149. if (gazer._isActionableMesh) {
  86150. multiplier = 3;
  86151. }
  86152. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  86153. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  86154. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  86155. var pickNormal = hit.getNormal();
  86156. // To avoid z-fighting
  86157. var deltaFighting = 0.002;
  86158. if (pickNormal) {
  86159. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  86160. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  86161. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  86162. }
  86163. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  86164. if (gazer._gazeTracker.position.x < 0) {
  86165. gazer._gazeTracker.position.x += deltaFighting;
  86166. }
  86167. else {
  86168. gazer._gazeTracker.position.x -= deltaFighting;
  86169. }
  86170. if (gazer._gazeTracker.position.y < 0) {
  86171. gazer._gazeTracker.position.y += deltaFighting;
  86172. }
  86173. else {
  86174. gazer._gazeTracker.position.y -= deltaFighting;
  86175. }
  86176. if (gazer._gazeTracker.position.z < 0) {
  86177. gazer._gazeTracker.position.z += deltaFighting;
  86178. }
  86179. else {
  86180. gazer._gazeTracker.position.z -= deltaFighting;
  86181. }
  86182. }
  86183. // Changing the size of the laser pointer based on the distance from the targetted point
  86184. gazer._updatePointerDistance(hit.distance);
  86185. }
  86186. else {
  86187. gazer._gazeTracker.isVisible = false;
  86188. }
  86189. if (hit && hit.pickedMesh) {
  86190. gazer._currentHit = hit;
  86191. if (gazer._pointerDownOnMeshAsked) {
  86192. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  86193. }
  86194. // The object selected is the floor, we're in a teleportation scenario
  86195. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  86196. // Moving the teleportation area to this targetted point
  86197. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  86198. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  86199. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  86200. }
  86201. gazer._currentMeshSelected = null;
  86202. if (gazer._teleportationRequestInitiated) {
  86203. this._moveTeleportationSelectorTo(hit, gazer);
  86204. }
  86205. return;
  86206. }
  86207. // If not, we're in a selection scenario
  86208. //this._teleportationAllowed = false;
  86209. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  86210. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  86211. this.onNewMeshPicked.notifyObservers(hit);
  86212. gazer._currentMeshSelected = hit.pickedMesh;
  86213. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  86214. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  86215. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  86216. gazer._isActionableMesh = true;
  86217. }
  86218. else {
  86219. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  86220. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  86221. gazer._isActionableMesh = false;
  86222. }
  86223. try {
  86224. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  86225. }
  86226. catch (err) {
  86227. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  86228. }
  86229. }
  86230. else {
  86231. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  86232. gazer._currentMeshSelected = null;
  86233. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  86234. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  86235. }
  86236. }
  86237. }
  86238. else {
  86239. gazer._currentHit = null;
  86240. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  86241. gazer._currentMeshSelected = null;
  86242. //this._teleportationAllowed = false;
  86243. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  86244. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  86245. }
  86246. };
  86247. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  86248. if (mesh) {
  86249. this.onSelectedMeshUnselected.notifyObservers(mesh);
  86250. }
  86251. };
  86252. /**
  86253. * Sets the color of the laser ray from the vr controllers.
  86254. * @param color new color for the ray.
  86255. */
  86256. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  86257. if (this.leftController) {
  86258. this.leftController._setLaserPointerColor(color);
  86259. }
  86260. if (this.rightController) {
  86261. this.rightController._setLaserPointerColor(color);
  86262. }
  86263. };
  86264. /**
  86265. * Sets the color of the ray from the vr headsets gaze.
  86266. * @param color new color for the ray.
  86267. */
  86268. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  86269. if (!this._cameraGazer._gazeTracker.material) {
  86270. return;
  86271. }
  86272. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  86273. if (this.leftController) {
  86274. this.leftController._gazeTracker.material.emissiveColor = color;
  86275. }
  86276. if (this.rightController) {
  86277. this.rightController._gazeTracker.material.emissiveColor = color;
  86278. }
  86279. };
  86280. /**
  86281. * Exits VR and disposes of the vr experience helper
  86282. */
  86283. VRExperienceHelper.prototype.dispose = function () {
  86284. if (this.isInVRMode) {
  86285. this.exitVR();
  86286. }
  86287. if (this._postProcessMove) {
  86288. this._postProcessMove.dispose();
  86289. }
  86290. if (this._webVRCamera) {
  86291. this._webVRCamera.dispose();
  86292. }
  86293. if (this._vrDeviceOrientationCamera) {
  86294. this._vrDeviceOrientationCamera.dispose();
  86295. }
  86296. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  86297. document.body.removeChild(this._btnVR);
  86298. }
  86299. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  86300. this._deviceOrientationCamera.dispose();
  86301. }
  86302. if (this._cameraGazer) {
  86303. this._cameraGazer.dispose();
  86304. }
  86305. if (this.leftController) {
  86306. this.leftController.dispose();
  86307. }
  86308. if (this.rightController) {
  86309. this.rightController.dispose();
  86310. }
  86311. if (this._teleportationTarget) {
  86312. this._teleportationTarget.dispose();
  86313. }
  86314. this._floorMeshesCollection = [];
  86315. document.removeEventListener("keydown", this._onKeyDown);
  86316. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  86317. window.removeEventListener("resize", this._onResize);
  86318. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  86319. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  86320. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  86321. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  86322. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  86323. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  86324. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  86325. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  86326. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  86327. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  86328. this._scene.unregisterBeforeRender(this.beforeRender);
  86329. };
  86330. /**
  86331. * Gets the name of the VRExperienceHelper class
  86332. * @returns "VRExperienceHelper"
  86333. */
  86334. VRExperienceHelper.prototype.getClassName = function () {
  86335. return "VRExperienceHelper";
  86336. };
  86337. return VRExperienceHelper;
  86338. }());
  86339. BABYLON.VRExperienceHelper = VRExperienceHelper;
  86340. })(BABYLON || (BABYLON = {}));
  86341. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  86342. "use strict";
  86343. // Mainly based on these 2 articles :
  86344. // 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
  86345. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  86346. var BABYLON;
  86347. (function (BABYLON) {
  86348. var JoystickAxis;
  86349. (function (JoystickAxis) {
  86350. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  86351. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  86352. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  86353. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  86354. var VirtualJoystick = /** @class */ (function () {
  86355. function VirtualJoystick(leftJoystick) {
  86356. var _this = this;
  86357. if (leftJoystick) {
  86358. this._leftJoystick = true;
  86359. }
  86360. else {
  86361. this._leftJoystick = false;
  86362. }
  86363. VirtualJoystick._globalJoystickIndex++;
  86364. // By default left & right arrow keys are moving the X
  86365. // and up & down keys are moving the Y
  86366. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  86367. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  86368. this.reverseLeftRight = false;
  86369. this.reverseUpDown = false;
  86370. // collections of pointers
  86371. this._touches = new BABYLON.StringDictionary();
  86372. this.deltaPosition = BABYLON.Vector3.Zero();
  86373. this._joystickSensibility = 25;
  86374. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  86375. this._onResize = function (evt) {
  86376. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  86377. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  86378. if (VirtualJoystick.vjCanvas) {
  86379. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  86380. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  86381. }
  86382. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  86383. };
  86384. // injecting a canvas element on top of the canvas 3D game
  86385. if (!VirtualJoystick.vjCanvas) {
  86386. window.addEventListener("resize", this._onResize, false);
  86387. VirtualJoystick.vjCanvas = document.createElement("canvas");
  86388. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  86389. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  86390. VirtualJoystick.vjCanvas.width = window.innerWidth;
  86391. VirtualJoystick.vjCanvas.height = window.innerHeight;
  86392. VirtualJoystick.vjCanvas.style.width = "100%";
  86393. VirtualJoystick.vjCanvas.style.height = "100%";
  86394. VirtualJoystick.vjCanvas.style.position = "absolute";
  86395. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  86396. VirtualJoystick.vjCanvas.style.top = "0px";
  86397. VirtualJoystick.vjCanvas.style.left = "0px";
  86398. VirtualJoystick.vjCanvas.style.zIndex = "5";
  86399. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  86400. // Support for jQuery PEP polyfill
  86401. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  86402. var context = VirtualJoystick.vjCanvas.getContext('2d');
  86403. if (!context) {
  86404. throw new Error("Unable to create canvas for virtual joystick");
  86405. }
  86406. VirtualJoystick.vjCanvasContext = context;
  86407. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  86408. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  86409. document.body.appendChild(VirtualJoystick.vjCanvas);
  86410. }
  86411. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  86412. this.pressed = false;
  86413. // default joystick color
  86414. this._joystickColor = "cyan";
  86415. this._joystickPointerID = -1;
  86416. // current joystick position
  86417. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  86418. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  86419. // origin joystick position
  86420. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  86421. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  86422. this._onPointerDownHandlerRef = function (evt) {
  86423. _this._onPointerDown(evt);
  86424. };
  86425. this._onPointerMoveHandlerRef = function (evt) {
  86426. _this._onPointerMove(evt);
  86427. };
  86428. this._onPointerUpHandlerRef = function (evt) {
  86429. _this._onPointerUp(evt);
  86430. };
  86431. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  86432. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  86433. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  86434. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  86435. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  86436. evt.preventDefault(); // Disables system menu
  86437. }, false);
  86438. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  86439. }
  86440. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  86441. this._joystickSensibility = newJoystickSensibility;
  86442. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  86443. };
  86444. VirtualJoystick.prototype._onPointerDown = function (e) {
  86445. var positionOnScreenCondition;
  86446. e.preventDefault();
  86447. if (this._leftJoystick === true) {
  86448. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  86449. }
  86450. else {
  86451. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  86452. }
  86453. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  86454. // First contact will be dedicated to the virtual joystick
  86455. this._joystickPointerID = e.pointerId;
  86456. this._joystickPointerStartPos.x = e.clientX;
  86457. this._joystickPointerStartPos.y = e.clientY;
  86458. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  86459. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  86460. this._deltaJoystickVector.x = 0;
  86461. this._deltaJoystickVector.y = 0;
  86462. this.pressed = true;
  86463. this._touches.add(e.pointerId.toString(), e);
  86464. }
  86465. else {
  86466. // You can only trigger the action buttons with a joystick declared
  86467. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  86468. this._action();
  86469. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  86470. }
  86471. }
  86472. };
  86473. VirtualJoystick.prototype._onPointerMove = function (e) {
  86474. // If the current pointer is the one associated to the joystick (first touch contact)
  86475. if (this._joystickPointerID == e.pointerId) {
  86476. this._joystickPointerPos.x = e.clientX;
  86477. this._joystickPointerPos.y = e.clientY;
  86478. this._deltaJoystickVector = this._joystickPointerPos.clone();
  86479. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  86480. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  86481. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  86482. switch (this._axisTargetedByLeftAndRight) {
  86483. case JoystickAxis.X:
  86484. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  86485. break;
  86486. case JoystickAxis.Y:
  86487. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  86488. break;
  86489. case JoystickAxis.Z:
  86490. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  86491. break;
  86492. }
  86493. var directionUpDown = this.reverseUpDown ? 1 : -1;
  86494. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  86495. switch (this._axisTargetedByUpAndDown) {
  86496. case JoystickAxis.X:
  86497. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  86498. break;
  86499. case JoystickAxis.Y:
  86500. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  86501. break;
  86502. case JoystickAxis.Z:
  86503. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  86504. break;
  86505. }
  86506. }
  86507. else {
  86508. var data = this._touches.get(e.pointerId.toString());
  86509. if (data) {
  86510. data.x = e.clientX;
  86511. data.y = e.clientY;
  86512. }
  86513. }
  86514. };
  86515. VirtualJoystick.prototype._onPointerUp = function (e) {
  86516. if (this._joystickPointerID == e.pointerId) {
  86517. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  86518. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  86519. this._joystickPointerID = -1;
  86520. this.pressed = false;
  86521. }
  86522. else {
  86523. var touch = this._touches.get(e.pointerId.toString());
  86524. if (touch) {
  86525. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  86526. }
  86527. }
  86528. this._deltaJoystickVector.x = 0;
  86529. this._deltaJoystickVector.y = 0;
  86530. this._touches.remove(e.pointerId.toString());
  86531. };
  86532. /**
  86533. * Change the color of the virtual joystick
  86534. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  86535. */
  86536. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  86537. this._joystickColor = newColor;
  86538. };
  86539. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  86540. this._action = action;
  86541. };
  86542. // Define which axis you'd like to control for left & right
  86543. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  86544. switch (axis) {
  86545. case JoystickAxis.X:
  86546. case JoystickAxis.Y:
  86547. case JoystickAxis.Z:
  86548. this._axisTargetedByLeftAndRight = axis;
  86549. break;
  86550. default:
  86551. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  86552. break;
  86553. }
  86554. };
  86555. // Define which axis you'd like to control for up & down
  86556. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  86557. switch (axis) {
  86558. case JoystickAxis.X:
  86559. case JoystickAxis.Y:
  86560. case JoystickAxis.Z:
  86561. this._axisTargetedByUpAndDown = axis;
  86562. break;
  86563. default:
  86564. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  86565. break;
  86566. }
  86567. };
  86568. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  86569. var _this = this;
  86570. if (this.pressed) {
  86571. this._touches.forEach(function (key, touch) {
  86572. if (touch.pointerId === _this._joystickPointerID) {
  86573. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  86574. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  86575. VirtualJoystick.vjCanvasContext.beginPath();
  86576. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  86577. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  86578. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  86579. VirtualJoystick.vjCanvasContext.stroke();
  86580. VirtualJoystick.vjCanvasContext.closePath();
  86581. VirtualJoystick.vjCanvasContext.beginPath();
  86582. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  86583. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  86584. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  86585. VirtualJoystick.vjCanvasContext.stroke();
  86586. VirtualJoystick.vjCanvasContext.closePath();
  86587. VirtualJoystick.vjCanvasContext.beginPath();
  86588. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  86589. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  86590. VirtualJoystick.vjCanvasContext.stroke();
  86591. VirtualJoystick.vjCanvasContext.closePath();
  86592. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  86593. }
  86594. else {
  86595. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  86596. VirtualJoystick.vjCanvasContext.beginPath();
  86597. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  86598. VirtualJoystick.vjCanvasContext.beginPath();
  86599. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  86600. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  86601. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  86602. VirtualJoystick.vjCanvasContext.stroke();
  86603. VirtualJoystick.vjCanvasContext.closePath();
  86604. touch.prevX = touch.x;
  86605. touch.prevY = touch.y;
  86606. }
  86607. ;
  86608. });
  86609. }
  86610. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  86611. };
  86612. VirtualJoystick.prototype.releaseCanvas = function () {
  86613. if (VirtualJoystick.vjCanvas) {
  86614. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  86615. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  86616. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  86617. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  86618. window.removeEventListener("resize", this._onResize);
  86619. document.body.removeChild(VirtualJoystick.vjCanvas);
  86620. VirtualJoystick.vjCanvas = null;
  86621. }
  86622. };
  86623. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  86624. VirtualJoystick._globalJoystickIndex = 0;
  86625. return VirtualJoystick;
  86626. }());
  86627. BABYLON.VirtualJoystick = VirtualJoystick;
  86628. })(BABYLON || (BABYLON = {}));
  86629. //# sourceMappingURL=babylon.virtualJoystick.js.map
  86630. "use strict";
  86631. var BABYLON;
  86632. (function (BABYLON) {
  86633. // We're mainly based on the logic defined into the FreeCamera code
  86634. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  86635. __extends(VirtualJoysticksCamera, _super);
  86636. function VirtualJoysticksCamera(name, position, scene) {
  86637. var _this = _super.call(this, name, position, scene) || this;
  86638. _this.inputs.addVirtualJoystick();
  86639. return _this;
  86640. }
  86641. VirtualJoysticksCamera.prototype.getClassName = function () {
  86642. return "VirtualJoysticksCamera";
  86643. };
  86644. return VirtualJoysticksCamera;
  86645. }(BABYLON.FreeCamera));
  86646. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  86647. })(BABYLON || (BABYLON = {}));
  86648. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  86649. "use strict";
  86650. var BABYLON;
  86651. (function (BABYLON) {
  86652. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  86653. function FreeCameraVirtualJoystickInput() {
  86654. }
  86655. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  86656. return this._leftjoystick;
  86657. };
  86658. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  86659. return this._rightjoystick;
  86660. };
  86661. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  86662. if (this._leftjoystick) {
  86663. var camera = this.camera;
  86664. var speed = camera._computeLocalCameraSpeed() * 50;
  86665. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  86666. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  86667. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  86668. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  86669. if (!this._leftjoystick.pressed) {
  86670. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  86671. }
  86672. if (!this._rightjoystick.pressed) {
  86673. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  86674. }
  86675. }
  86676. };
  86677. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  86678. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  86679. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  86680. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  86681. this._leftjoystick.setJoystickSensibility(0.15);
  86682. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  86683. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  86684. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  86685. this._rightjoystick.reverseUpDown = true;
  86686. this._rightjoystick.setJoystickSensibility(0.05);
  86687. this._rightjoystick.setJoystickColor("yellow");
  86688. };
  86689. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  86690. this._leftjoystick.releaseCanvas();
  86691. this._rightjoystick.releaseCanvas();
  86692. };
  86693. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  86694. return "FreeCameraVirtualJoystickInput";
  86695. };
  86696. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  86697. return "virtualJoystick";
  86698. };
  86699. return FreeCameraVirtualJoystickInput;
  86700. }());
  86701. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  86702. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  86703. })(BABYLON || (BABYLON = {}));
  86704. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  86705. "use strict";
  86706. var BABYLON;
  86707. (function (BABYLON) {
  86708. var SimplificationSettings = /** @class */ (function () {
  86709. function SimplificationSettings(quality, distance, optimizeMesh) {
  86710. this.quality = quality;
  86711. this.distance = distance;
  86712. this.optimizeMesh = optimizeMesh;
  86713. }
  86714. return SimplificationSettings;
  86715. }());
  86716. BABYLON.SimplificationSettings = SimplificationSettings;
  86717. var SimplificationQueue = /** @class */ (function () {
  86718. function SimplificationQueue() {
  86719. this.running = false;
  86720. this._simplificationArray = [];
  86721. }
  86722. SimplificationQueue.prototype.addTask = function (task) {
  86723. this._simplificationArray.push(task);
  86724. };
  86725. SimplificationQueue.prototype.executeNext = function () {
  86726. var task = this._simplificationArray.pop();
  86727. if (task) {
  86728. this.running = true;
  86729. this.runSimplification(task);
  86730. }
  86731. else {
  86732. this.running = false;
  86733. }
  86734. };
  86735. SimplificationQueue.prototype.runSimplification = function (task) {
  86736. var _this = this;
  86737. if (task.parallelProcessing) {
  86738. //parallel simplifier
  86739. task.settings.forEach(function (setting) {
  86740. var simplifier = _this.getSimplifier(task);
  86741. simplifier.simplify(setting, function (newMesh) {
  86742. task.mesh.addLODLevel(setting.distance, newMesh);
  86743. newMesh.isVisible = true;
  86744. //check if it is the last
  86745. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  86746. //all done, run the success callback.
  86747. task.successCallback();
  86748. }
  86749. _this.executeNext();
  86750. });
  86751. });
  86752. }
  86753. else {
  86754. //single simplifier.
  86755. var simplifier = this.getSimplifier(task);
  86756. var runDecimation = function (setting, callback) {
  86757. simplifier.simplify(setting, function (newMesh) {
  86758. task.mesh.addLODLevel(setting.distance, newMesh);
  86759. newMesh.isVisible = true;
  86760. //run the next quality level
  86761. callback();
  86762. });
  86763. };
  86764. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  86765. runDecimation(task.settings[loop.index], function () {
  86766. loop.executeNext();
  86767. });
  86768. }, function () {
  86769. //execution ended, run the success callback.
  86770. if (task.successCallback) {
  86771. task.successCallback();
  86772. }
  86773. _this.executeNext();
  86774. });
  86775. }
  86776. };
  86777. SimplificationQueue.prototype.getSimplifier = function (task) {
  86778. switch (task.simplificationType) {
  86779. case SimplificationType.QUADRATIC:
  86780. default:
  86781. return new QuadraticErrorSimplification(task.mesh);
  86782. }
  86783. };
  86784. return SimplificationQueue;
  86785. }());
  86786. BABYLON.SimplificationQueue = SimplificationQueue;
  86787. /**
  86788. * The implemented types of simplification.
  86789. * At the moment only Quadratic Error Decimation is implemented.
  86790. */
  86791. var SimplificationType;
  86792. (function (SimplificationType) {
  86793. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  86794. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  86795. var DecimationTriangle = /** @class */ (function () {
  86796. function DecimationTriangle(vertices) {
  86797. this.vertices = vertices;
  86798. this.error = new Array(4);
  86799. this.deleted = false;
  86800. this.isDirty = false;
  86801. this.deletePending = false;
  86802. this.borderFactor = 0;
  86803. }
  86804. return DecimationTriangle;
  86805. }());
  86806. BABYLON.DecimationTriangle = DecimationTriangle;
  86807. var DecimationVertex = /** @class */ (function () {
  86808. function DecimationVertex(position, id) {
  86809. this.position = position;
  86810. this.id = id;
  86811. this.isBorder = true;
  86812. this.q = new QuadraticMatrix();
  86813. this.triangleCount = 0;
  86814. this.triangleStart = 0;
  86815. this.originalOffsets = [];
  86816. }
  86817. DecimationVertex.prototype.updatePosition = function (newPosition) {
  86818. this.position.copyFrom(newPosition);
  86819. };
  86820. return DecimationVertex;
  86821. }());
  86822. BABYLON.DecimationVertex = DecimationVertex;
  86823. var QuadraticMatrix = /** @class */ (function () {
  86824. function QuadraticMatrix(data) {
  86825. this.data = new Array(10);
  86826. for (var i = 0; i < 10; ++i) {
  86827. if (data && data[i]) {
  86828. this.data[i] = data[i];
  86829. }
  86830. else {
  86831. this.data[i] = 0;
  86832. }
  86833. }
  86834. }
  86835. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  86836. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  86837. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  86838. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  86839. return det;
  86840. };
  86841. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  86842. for (var i = 0; i < 10; ++i) {
  86843. this.data[i] += matrix.data[i];
  86844. }
  86845. };
  86846. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  86847. for (var i = 0; i < 10; ++i) {
  86848. this.data[i] += data[i];
  86849. }
  86850. };
  86851. QuadraticMatrix.prototype.add = function (matrix) {
  86852. var m = new QuadraticMatrix();
  86853. for (var i = 0; i < 10; ++i) {
  86854. m.data[i] = this.data[i] + matrix.data[i];
  86855. }
  86856. return m;
  86857. };
  86858. QuadraticMatrix.FromData = function (a, b, c, d) {
  86859. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  86860. };
  86861. //returning an array to avoid garbage collection
  86862. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  86863. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  86864. };
  86865. return QuadraticMatrix;
  86866. }());
  86867. BABYLON.QuadraticMatrix = QuadraticMatrix;
  86868. var Reference = /** @class */ (function () {
  86869. function Reference(vertexId, triangleId) {
  86870. this.vertexId = vertexId;
  86871. this.triangleId = triangleId;
  86872. }
  86873. return Reference;
  86874. }());
  86875. BABYLON.Reference = Reference;
  86876. /**
  86877. * An implementation of the Quadratic Error simplification algorithm.
  86878. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  86879. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  86880. * @author RaananW
  86881. */
  86882. var QuadraticErrorSimplification = /** @class */ (function () {
  86883. function QuadraticErrorSimplification(_mesh) {
  86884. this._mesh = _mesh;
  86885. this.syncIterations = 5000;
  86886. this.aggressiveness = 7;
  86887. this.decimationIterations = 100;
  86888. this.boundingBoxEpsilon = BABYLON.Epsilon;
  86889. }
  86890. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  86891. var _this = this;
  86892. this.initDecimatedMesh();
  86893. //iterating through the submeshes array, one after the other.
  86894. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  86895. _this.initWithMesh(loop.index, function () {
  86896. _this.runDecimation(settings, loop.index, function () {
  86897. loop.executeNext();
  86898. });
  86899. }, settings.optimizeMesh);
  86900. }, function () {
  86901. setTimeout(function () {
  86902. successCallback(_this._reconstructedMesh);
  86903. }, 0);
  86904. });
  86905. };
  86906. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  86907. var _this = this;
  86908. var targetCount = ~~(this.triangles.length * settings.quality);
  86909. var deletedTriangles = 0;
  86910. var triangleCount = this.triangles.length;
  86911. var iterationFunction = function (iteration, callback) {
  86912. setTimeout(function () {
  86913. if (iteration % 5 === 0) {
  86914. _this.updateMesh(iteration === 0);
  86915. }
  86916. for (var i = 0; i < _this.triangles.length; ++i) {
  86917. _this.triangles[i].isDirty = false;
  86918. }
  86919. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  86920. var trianglesIterator = function (i) {
  86921. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  86922. var t = _this.triangles[tIdx];
  86923. if (!t)
  86924. return;
  86925. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  86926. return;
  86927. }
  86928. for (var j = 0; j < 3; ++j) {
  86929. if (t.error[j] < threshold) {
  86930. var deleted0 = [];
  86931. var deleted1 = [];
  86932. var v0 = t.vertices[j];
  86933. var v1 = t.vertices[(j + 1) % 3];
  86934. if (v0.isBorder || v1.isBorder)
  86935. continue;
  86936. var p = BABYLON.Vector3.Zero();
  86937. var n = BABYLON.Vector3.Zero();
  86938. var uv = BABYLON.Vector2.Zero();
  86939. var color = new BABYLON.Color4(0, 0, 0, 1);
  86940. _this.calculateError(v0, v1, p, n, uv, color);
  86941. var delTr = new Array();
  86942. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  86943. continue;
  86944. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  86945. continue;
  86946. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  86947. continue;
  86948. var uniqueArray = new Array();
  86949. delTr.forEach(function (deletedT) {
  86950. if (uniqueArray.indexOf(deletedT) === -1) {
  86951. deletedT.deletePending = true;
  86952. uniqueArray.push(deletedT);
  86953. }
  86954. });
  86955. if (uniqueArray.length % 2 !== 0) {
  86956. continue;
  86957. }
  86958. v0.q = v1.q.add(v0.q);
  86959. v0.updatePosition(p);
  86960. var tStart = _this.references.length;
  86961. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  86962. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  86963. var tCount = _this.references.length - tStart;
  86964. if (tCount <= v0.triangleCount) {
  86965. if (tCount) {
  86966. for (var c = 0; c < tCount; c++) {
  86967. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  86968. }
  86969. }
  86970. }
  86971. else {
  86972. v0.triangleStart = tStart;
  86973. }
  86974. v0.triangleCount = tCount;
  86975. break;
  86976. }
  86977. }
  86978. };
  86979. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  86980. }, 0);
  86981. };
  86982. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  86983. if (triangleCount - deletedTriangles <= targetCount)
  86984. loop.breakLoop();
  86985. else {
  86986. iterationFunction(loop.index, function () {
  86987. loop.executeNext();
  86988. });
  86989. }
  86990. }, function () {
  86991. setTimeout(function () {
  86992. //reconstruct this part of the mesh
  86993. _this.reconstructMesh(submeshIndex);
  86994. successCallback();
  86995. }, 0);
  86996. });
  86997. };
  86998. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  86999. var _this = this;
  87000. this.vertices = [];
  87001. this.triangles = [];
  87002. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  87003. var indices = this._mesh.getIndices();
  87004. var submesh = this._mesh.subMeshes[submeshIndex];
  87005. var findInVertices = function (positionToSearch) {
  87006. if (optimizeMesh) {
  87007. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  87008. if (_this.vertices[ii].position.equals(positionToSearch)) {
  87009. return _this.vertices[ii];
  87010. }
  87011. }
  87012. }
  87013. return null;
  87014. };
  87015. var vertexReferences = [];
  87016. var vertexInit = function (i) {
  87017. if (!positionData) {
  87018. return;
  87019. }
  87020. var offset = i + submesh.verticesStart;
  87021. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  87022. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  87023. vertex.originalOffsets.push(offset);
  87024. if (vertex.id === _this.vertices.length) {
  87025. _this.vertices.push(vertex);
  87026. }
  87027. vertexReferences.push(vertex.id);
  87028. };
  87029. //var totalVertices = mesh.getTotalVertices();
  87030. var totalVertices = submesh.verticesCount;
  87031. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  87032. var indicesInit = function (i) {
  87033. if (!indices) {
  87034. return;
  87035. }
  87036. var offset = (submesh.indexStart / 3) + i;
  87037. var pos = (offset * 3);
  87038. var i0 = indices[pos + 0];
  87039. var i1 = indices[pos + 1];
  87040. var i2 = indices[pos + 2];
  87041. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  87042. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  87043. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  87044. var triangle = new DecimationTriangle([v0, v1, v2]);
  87045. triangle.originalOffset = pos;
  87046. _this.triangles.push(triangle);
  87047. };
  87048. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  87049. _this.init(callback);
  87050. });
  87051. });
  87052. };
  87053. QuadraticErrorSimplification.prototype.init = function (callback) {
  87054. var _this = this;
  87055. var triangleInit1 = function (i) {
  87056. var t = _this.triangles[i];
  87057. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  87058. for (var j = 0; j < 3; j++) {
  87059. 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))));
  87060. }
  87061. };
  87062. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  87063. var triangleInit2 = function (i) {
  87064. var t = _this.triangles[i];
  87065. for (var j = 0; j < 3; ++j) {
  87066. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  87067. }
  87068. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  87069. };
  87070. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  87071. callback();
  87072. });
  87073. });
  87074. };
  87075. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  87076. var newTriangles = [];
  87077. var i;
  87078. for (i = 0; i < this.vertices.length; ++i) {
  87079. this.vertices[i].triangleCount = 0;
  87080. }
  87081. var t;
  87082. var j;
  87083. for (i = 0; i < this.triangles.length; ++i) {
  87084. if (!this.triangles[i].deleted) {
  87085. t = this.triangles[i];
  87086. for (j = 0; j < 3; ++j) {
  87087. t.vertices[j].triangleCount = 1;
  87088. }
  87089. newTriangles.push(t);
  87090. }
  87091. }
  87092. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  87093. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  87094. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  87095. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  87096. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  87097. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  87098. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  87099. var vertexCount = 0;
  87100. for (i = 0; i < this.vertices.length; ++i) {
  87101. var vertex = this.vertices[i];
  87102. vertex.id = vertexCount;
  87103. if (vertex.triangleCount) {
  87104. vertex.originalOffsets.forEach(function (originalOffset) {
  87105. if (!normalData) {
  87106. return;
  87107. }
  87108. newPositionData.push(vertex.position.x);
  87109. newPositionData.push(vertex.position.y);
  87110. newPositionData.push(vertex.position.z);
  87111. newNormalData.push(normalData[originalOffset * 3]);
  87112. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  87113. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  87114. if (uvs && uvs.length) {
  87115. newUVsData.push(uvs[(originalOffset * 2)]);
  87116. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  87117. }
  87118. else if (colorsData && colorsData.length) {
  87119. newColorsData.push(colorsData[(originalOffset * 4)]);
  87120. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  87121. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  87122. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  87123. }
  87124. ++vertexCount;
  87125. });
  87126. }
  87127. }
  87128. var startingIndex = this._reconstructedMesh.getTotalIndices();
  87129. var startingVertex = this._reconstructedMesh.getTotalVertices();
  87130. var submeshesArray = this._reconstructedMesh.subMeshes;
  87131. this._reconstructedMesh.subMeshes = [];
  87132. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  87133. var originalIndices = this._mesh.getIndices();
  87134. for (i = 0; i < newTriangles.length; ++i) {
  87135. t = newTriangles[i]; //now get the new referencing point for each vertex
  87136. [0, 1, 2].forEach(function (idx) {
  87137. var id = originalIndices[t.originalOffset + idx];
  87138. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  87139. if (offset < 0)
  87140. offset = 0;
  87141. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  87142. });
  87143. }
  87144. //overwriting the old vertex buffers and indices.
  87145. this._reconstructedMesh.setIndices(newIndicesArray);
  87146. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  87147. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  87148. if (newUVsData.length > 0)
  87149. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  87150. if (newColorsData.length > 0)
  87151. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  87152. //create submesh
  87153. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  87154. if (submeshIndex > 0) {
  87155. this._reconstructedMesh.subMeshes = [];
  87156. submeshesArray.forEach(function (submesh) {
  87157. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  87158. });
  87159. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  87160. }
  87161. };
  87162. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  87163. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  87164. this._reconstructedMesh.material = this._mesh.material;
  87165. this._reconstructedMesh.parent = this._mesh.parent;
  87166. this._reconstructedMesh.isVisible = false;
  87167. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  87168. };
  87169. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  87170. for (var i = 0; i < vertex1.triangleCount; ++i) {
  87171. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  87172. if (t.deleted)
  87173. continue;
  87174. var s = this.references[vertex1.triangleStart + i].vertexId;
  87175. var v1 = t.vertices[(s + 1) % 3];
  87176. var v2 = t.vertices[(s + 2) % 3];
  87177. if ((v1 === vertex2 || v2 === vertex2)) {
  87178. deletedArray[i] = true;
  87179. delTr.push(t);
  87180. continue;
  87181. }
  87182. var d1 = v1.position.subtract(point);
  87183. d1 = d1.normalize();
  87184. var d2 = v2.position.subtract(point);
  87185. d2 = d2.normalize();
  87186. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  87187. return true;
  87188. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  87189. deletedArray[i] = false;
  87190. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  87191. return true;
  87192. }
  87193. return false;
  87194. };
  87195. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  87196. var newDeleted = deletedTriangles;
  87197. for (var i = 0; i < vertex.triangleCount; ++i) {
  87198. var ref = this.references[vertex.triangleStart + i];
  87199. var t = this.triangles[ref.triangleId];
  87200. if (t.deleted)
  87201. continue;
  87202. if (deletedArray[i] && t.deletePending) {
  87203. t.deleted = true;
  87204. newDeleted++;
  87205. continue;
  87206. }
  87207. t.vertices[ref.vertexId] = origVertex;
  87208. t.isDirty = true;
  87209. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  87210. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  87211. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  87212. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  87213. this.references.push(ref);
  87214. }
  87215. return newDeleted;
  87216. };
  87217. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  87218. for (var i = 0; i < this.vertices.length; ++i) {
  87219. var vCount = [];
  87220. var vId = [];
  87221. var v = this.vertices[i];
  87222. var j;
  87223. for (j = 0; j < v.triangleCount; ++j) {
  87224. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  87225. for (var ii = 0; ii < 3; ii++) {
  87226. var ofs = 0;
  87227. var vv = triangle.vertices[ii];
  87228. while (ofs < vCount.length) {
  87229. if (vId[ofs] === vv.id)
  87230. break;
  87231. ++ofs;
  87232. }
  87233. if (ofs === vCount.length) {
  87234. vCount.push(1);
  87235. vId.push(vv.id);
  87236. }
  87237. else {
  87238. vCount[ofs]++;
  87239. }
  87240. }
  87241. }
  87242. for (j = 0; j < vCount.length; ++j) {
  87243. if (vCount[j] === 1) {
  87244. this.vertices[vId[j]].isBorder = true;
  87245. }
  87246. else {
  87247. this.vertices[vId[j]].isBorder = false;
  87248. }
  87249. }
  87250. }
  87251. };
  87252. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  87253. if (identifyBorders === void 0) { identifyBorders = false; }
  87254. var i;
  87255. if (!identifyBorders) {
  87256. var newTrianglesVector = [];
  87257. for (i = 0; i < this.triangles.length; ++i) {
  87258. if (!this.triangles[i].deleted) {
  87259. newTrianglesVector.push(this.triangles[i]);
  87260. }
  87261. }
  87262. this.triangles = newTrianglesVector;
  87263. }
  87264. for (i = 0; i < this.vertices.length; ++i) {
  87265. this.vertices[i].triangleCount = 0;
  87266. this.vertices[i].triangleStart = 0;
  87267. }
  87268. var t;
  87269. var j;
  87270. var v;
  87271. for (i = 0; i < this.triangles.length; ++i) {
  87272. t = this.triangles[i];
  87273. for (j = 0; j < 3; ++j) {
  87274. v = t.vertices[j];
  87275. v.triangleCount++;
  87276. }
  87277. }
  87278. var tStart = 0;
  87279. for (i = 0; i < this.vertices.length; ++i) {
  87280. this.vertices[i].triangleStart = tStart;
  87281. tStart += this.vertices[i].triangleCount;
  87282. this.vertices[i].triangleCount = 0;
  87283. }
  87284. var newReferences = new Array(this.triangles.length * 3);
  87285. for (i = 0; i < this.triangles.length; ++i) {
  87286. t = this.triangles[i];
  87287. for (j = 0; j < 3; ++j) {
  87288. v = t.vertices[j];
  87289. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  87290. v.triangleCount++;
  87291. }
  87292. }
  87293. this.references = newReferences;
  87294. if (identifyBorders) {
  87295. this.identifyBorder();
  87296. }
  87297. };
  87298. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  87299. var x = point.x;
  87300. var y = point.y;
  87301. var z = point.z;
  87302. 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
  87303. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  87304. };
  87305. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  87306. var q = vertex1.q.add(vertex2.q);
  87307. var border = vertex1.isBorder && vertex2.isBorder;
  87308. var error = 0;
  87309. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  87310. if (qDet !== 0 && !border) {
  87311. if (!pointResult) {
  87312. pointResult = BABYLON.Vector3.Zero();
  87313. }
  87314. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  87315. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  87316. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  87317. error = this.vertexError(q, pointResult);
  87318. }
  87319. else {
  87320. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  87321. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  87322. var error1 = this.vertexError(q, vertex1.position);
  87323. var error2 = this.vertexError(q, vertex2.position);
  87324. var error3 = this.vertexError(q, p3);
  87325. error = Math.min(error1, error2, error3);
  87326. if (error === error1) {
  87327. if (pointResult) {
  87328. pointResult.copyFrom(vertex1.position);
  87329. }
  87330. }
  87331. else if (error === error2) {
  87332. if (pointResult) {
  87333. pointResult.copyFrom(vertex2.position);
  87334. }
  87335. }
  87336. else {
  87337. if (pointResult) {
  87338. pointResult.copyFrom(p3);
  87339. }
  87340. }
  87341. }
  87342. return error;
  87343. };
  87344. return QuadraticErrorSimplification;
  87345. }());
  87346. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  87347. })(BABYLON || (BABYLON = {}));
  87348. //# sourceMappingURL=babylon.meshSimplification.js.map
  87349. "use strict";
  87350. var BABYLON;
  87351. (function (BABYLON) {
  87352. var MeshLODLevel = /** @class */ (function () {
  87353. function MeshLODLevel(distance, mesh) {
  87354. this.distance = distance;
  87355. this.mesh = mesh;
  87356. }
  87357. return MeshLODLevel;
  87358. }());
  87359. BABYLON.MeshLODLevel = MeshLODLevel;
  87360. })(BABYLON || (BABYLON = {}));
  87361. //# sourceMappingURL=babylon.meshLODLevel.js.map
  87362. "use strict";
  87363. var BABYLON;
  87364. (function (BABYLON) {
  87365. /**
  87366. * Defines the root class used to create scene optimization to use with SceneOptimizer
  87367. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  87368. */
  87369. var SceneOptimization = /** @class */ (function () {
  87370. /**
  87371. * Creates the SceneOptimization object
  87372. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  87373. * @param desc defines the description associated with the optimization
  87374. */
  87375. function SceneOptimization(
  87376. /**
  87377. * Defines the priority of this optimization (0 by default which means first in the list)
  87378. */
  87379. priority) {
  87380. if (priority === void 0) { priority = 0; }
  87381. this.priority = priority;
  87382. }
  87383. /**
  87384. * Gets a string describing the action executed by the current optimization
  87385. * @returns description string
  87386. */
  87387. SceneOptimization.prototype.getDescription = function () {
  87388. return "";
  87389. };
  87390. /**
  87391. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  87392. * @param scene defines the current scene where to apply this optimization
  87393. * @param optimizer defines the current optimizer
  87394. * @returns true if everything that can be done was applied
  87395. */
  87396. SceneOptimization.prototype.apply = function (scene, optimizer) {
  87397. return true;
  87398. };
  87399. ;
  87400. return SceneOptimization;
  87401. }());
  87402. BABYLON.SceneOptimization = SceneOptimization;
  87403. /**
  87404. * Defines an optimization used to reduce the size of render target textures
  87405. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  87406. */
  87407. var TextureOptimization = /** @class */ (function (_super) {
  87408. __extends(TextureOptimization, _super);
  87409. /**
  87410. * Creates the TextureOptimization object
  87411. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  87412. * @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
  87413. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  87414. */
  87415. function TextureOptimization(
  87416. /**
  87417. * Defines the priority of this optimization (0 by default which means first in the list)
  87418. */
  87419. priority,
  87420. /**
  87421. * 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
  87422. */
  87423. maximumSize,
  87424. /**
  87425. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  87426. */
  87427. step) {
  87428. if (priority === void 0) { priority = 0; }
  87429. if (maximumSize === void 0) { maximumSize = 1024; }
  87430. if (step === void 0) { step = 0.5; }
  87431. var _this = _super.call(this, priority) || this;
  87432. _this.priority = priority;
  87433. _this.maximumSize = maximumSize;
  87434. _this.step = step;
  87435. return _this;
  87436. }
  87437. /**
  87438. * Gets a string describing the action executed by the current optimization
  87439. * @returns description string
  87440. */
  87441. TextureOptimization.prototype.getDescription = function () {
  87442. return "Reducing render target texture size to " + this.maximumSize;
  87443. };
  87444. /**
  87445. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  87446. * @param scene defines the current scene where to apply this optimization
  87447. * @param optimizer defines the current optimizer
  87448. * @returns true if everything that can be done was applied
  87449. */
  87450. TextureOptimization.prototype.apply = function (scene, optimizer) {
  87451. var allDone = true;
  87452. for (var index = 0; index < scene.textures.length; index++) {
  87453. var texture = scene.textures[index];
  87454. if (!texture.canRescale || texture.getContext) {
  87455. continue;
  87456. }
  87457. var currentSize = texture.getSize();
  87458. var maxDimension = Math.max(currentSize.width, currentSize.height);
  87459. if (maxDimension > this.maximumSize) {
  87460. texture.scale(this.step);
  87461. allDone = false;
  87462. }
  87463. }
  87464. return allDone;
  87465. };
  87466. return TextureOptimization;
  87467. }(SceneOptimization));
  87468. BABYLON.TextureOptimization = TextureOptimization;
  87469. /**
  87470. * Defines an optimization used to increase or decrease the rendering resolution
  87471. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  87472. */
  87473. var HardwareScalingOptimization = /** @class */ (function (_super) {
  87474. __extends(HardwareScalingOptimization, _super);
  87475. /**
  87476. * Creates the HardwareScalingOptimization object
  87477. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  87478. * @param maximumScale defines the maximum scale to use (2 by default)
  87479. * @param step defines the step to use between two passes (0.5 by default)
  87480. */
  87481. function HardwareScalingOptimization(
  87482. /**
  87483. * Defines the priority of this optimization (0 by default which means first in the list)
  87484. */
  87485. priority,
  87486. /**
  87487. * Defines the maximum scale to use (2 by default)
  87488. */
  87489. maximumScale,
  87490. /**
  87491. * Defines the step to use between two passes (0.5 by default)
  87492. */
  87493. step) {
  87494. if (priority === void 0) { priority = 0; }
  87495. if (maximumScale === void 0) { maximumScale = 2; }
  87496. if (step === void 0) { step = 0.25; }
  87497. var _this = _super.call(this, priority) || this;
  87498. _this.priority = priority;
  87499. _this.maximumScale = maximumScale;
  87500. _this.step = step;
  87501. _this._currentScale = -1;
  87502. _this._directionOffset = 1;
  87503. return _this;
  87504. }
  87505. /**
  87506. * Gets a string describing the action executed by the current optimization
  87507. * @return description string
  87508. */
  87509. HardwareScalingOptimization.prototype.getDescription = function () {
  87510. return "Setting hardware scaling level to " + this._currentScale;
  87511. };
  87512. /**
  87513. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  87514. * @param scene defines the current scene where to apply this optimization
  87515. * @param optimizer defines the current optimizer
  87516. * @returns true if everything that can be done was applied
  87517. */
  87518. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  87519. if (this._currentScale === -1) {
  87520. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  87521. if (this._currentScale > this.maximumScale) {
  87522. this._directionOffset = -1;
  87523. }
  87524. }
  87525. this._currentScale += this._directionOffset * this.step;
  87526. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  87527. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  87528. };
  87529. ;
  87530. return HardwareScalingOptimization;
  87531. }(SceneOptimization));
  87532. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  87533. /**
  87534. * Defines an optimization used to remove shadows
  87535. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  87536. */
  87537. var ShadowsOptimization = /** @class */ (function (_super) {
  87538. __extends(ShadowsOptimization, _super);
  87539. function ShadowsOptimization() {
  87540. return _super !== null && _super.apply(this, arguments) || this;
  87541. }
  87542. /**
  87543. * Gets a string describing the action executed by the current optimization
  87544. * @return description string
  87545. */
  87546. ShadowsOptimization.prototype.getDescription = function () {
  87547. return "Turning shadows on/off";
  87548. };
  87549. /**
  87550. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  87551. * @param scene defines the current scene where to apply this optimization
  87552. * @param optimizer defines the current optimizer
  87553. * @returns true if everything that can be done was applied
  87554. */
  87555. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  87556. scene.shadowsEnabled = optimizer.isInImprovementMode;
  87557. return true;
  87558. };
  87559. ;
  87560. return ShadowsOptimization;
  87561. }(SceneOptimization));
  87562. BABYLON.ShadowsOptimization = ShadowsOptimization;
  87563. /**
  87564. * Defines an optimization used to turn post-processes off
  87565. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  87566. */
  87567. var PostProcessesOptimization = /** @class */ (function (_super) {
  87568. __extends(PostProcessesOptimization, _super);
  87569. function PostProcessesOptimization() {
  87570. return _super !== null && _super.apply(this, arguments) || this;
  87571. }
  87572. /**
  87573. * Gets a string describing the action executed by the current optimization
  87574. * @return description string
  87575. */
  87576. PostProcessesOptimization.prototype.getDescription = function () {
  87577. return "Turning post-processes on/off";
  87578. };
  87579. /**
  87580. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  87581. * @param scene defines the current scene where to apply this optimization
  87582. * @param optimizer defines the current optimizer
  87583. * @returns true if everything that can be done was applied
  87584. */
  87585. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  87586. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  87587. return true;
  87588. };
  87589. ;
  87590. return PostProcessesOptimization;
  87591. }(SceneOptimization));
  87592. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  87593. /**
  87594. * Defines an optimization used to turn lens flares off
  87595. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  87596. */
  87597. var LensFlaresOptimization = /** @class */ (function (_super) {
  87598. __extends(LensFlaresOptimization, _super);
  87599. function LensFlaresOptimization() {
  87600. return _super !== null && _super.apply(this, arguments) || this;
  87601. }
  87602. /**
  87603. * Gets a string describing the action executed by the current optimization
  87604. * @return description string
  87605. */
  87606. LensFlaresOptimization.prototype.getDescription = function () {
  87607. return "Turning lens flares on/off";
  87608. };
  87609. /**
  87610. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  87611. * @param scene defines the current scene where to apply this optimization
  87612. * @param optimizer defines the current optimizer
  87613. * @returns true if everything that can be done was applied
  87614. */
  87615. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  87616. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  87617. return true;
  87618. };
  87619. ;
  87620. return LensFlaresOptimization;
  87621. }(SceneOptimization));
  87622. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  87623. /**
  87624. * Defines an optimization based on user defined callback.
  87625. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  87626. */
  87627. var CustomOptimization = /** @class */ (function (_super) {
  87628. __extends(CustomOptimization, _super);
  87629. function CustomOptimization() {
  87630. return _super !== null && _super.apply(this, arguments) || this;
  87631. }
  87632. /**
  87633. * Gets a string describing the action executed by the current optimization
  87634. * @returns description string
  87635. */
  87636. CustomOptimization.prototype.getDescription = function () {
  87637. if (this.onGetDescription) {
  87638. return this.onGetDescription();
  87639. }
  87640. return "Running user defined callback";
  87641. };
  87642. /**
  87643. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  87644. * @param scene defines the current scene where to apply this optimization
  87645. * @param optimizer defines the current optimizer
  87646. * @returns true if everything that can be done was applied
  87647. */
  87648. CustomOptimization.prototype.apply = function (scene, optimizer) {
  87649. if (this.onApply) {
  87650. return this.onApply(scene, optimizer);
  87651. }
  87652. return true;
  87653. };
  87654. ;
  87655. return CustomOptimization;
  87656. }(SceneOptimization));
  87657. BABYLON.CustomOptimization = CustomOptimization;
  87658. /**
  87659. * Defines an optimization used to turn particles off
  87660. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  87661. */
  87662. var ParticlesOptimization = /** @class */ (function (_super) {
  87663. __extends(ParticlesOptimization, _super);
  87664. function ParticlesOptimization() {
  87665. return _super !== null && _super.apply(this, arguments) || this;
  87666. }
  87667. /**
  87668. * Gets a string describing the action executed by the current optimization
  87669. * @return description string
  87670. */
  87671. ParticlesOptimization.prototype.getDescription = function () {
  87672. return "Turning particles on/off";
  87673. };
  87674. /**
  87675. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  87676. * @param scene defines the current scene where to apply this optimization
  87677. * @param optimizer defines the current optimizer
  87678. * @returns true if everything that can be done was applied
  87679. */
  87680. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  87681. scene.particlesEnabled = optimizer.isInImprovementMode;
  87682. return true;
  87683. };
  87684. ;
  87685. return ParticlesOptimization;
  87686. }(SceneOptimization));
  87687. BABYLON.ParticlesOptimization = ParticlesOptimization;
  87688. /**
  87689. * Defines an optimization used to turn render targets off
  87690. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  87691. */
  87692. var RenderTargetsOptimization = /** @class */ (function (_super) {
  87693. __extends(RenderTargetsOptimization, _super);
  87694. function RenderTargetsOptimization() {
  87695. return _super !== null && _super.apply(this, arguments) || this;
  87696. }
  87697. /**
  87698. * Gets a string describing the action executed by the current optimization
  87699. * @return description string
  87700. */
  87701. RenderTargetsOptimization.prototype.getDescription = function () {
  87702. return "Turning render targets off";
  87703. };
  87704. /**
  87705. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  87706. * @param scene defines the current scene where to apply this optimization
  87707. * @param optimizer defines the current optimizer
  87708. * @returns true if everything that can be done was applied
  87709. */
  87710. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  87711. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  87712. return true;
  87713. };
  87714. ;
  87715. return RenderTargetsOptimization;
  87716. }(SceneOptimization));
  87717. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  87718. /**
  87719. * Defines an optimization used to merge meshes with compatible materials
  87720. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  87721. */
  87722. var MergeMeshesOptimization = /** @class */ (function (_super) {
  87723. __extends(MergeMeshesOptimization, _super);
  87724. function MergeMeshesOptimization() {
  87725. var _this = _super !== null && _super.apply(this, arguments) || this;
  87726. _this._canBeMerged = function (abstractMesh) {
  87727. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  87728. return false;
  87729. }
  87730. var mesh = abstractMesh;
  87731. if (!mesh.isVisible || !mesh.isEnabled()) {
  87732. return false;
  87733. }
  87734. if (mesh.instances.length > 0) {
  87735. return false;
  87736. }
  87737. if (mesh.skeleton || mesh.hasLODLevels) {
  87738. return false;
  87739. }
  87740. if (mesh.parent) {
  87741. return false;
  87742. }
  87743. return true;
  87744. };
  87745. return _this;
  87746. }
  87747. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  87748. /**
  87749. * Gets or sets a boolean which defines if optimization octree has to be updated
  87750. */
  87751. get: function () {
  87752. return MergeMeshesOptimization._UpdateSelectionTree;
  87753. },
  87754. /**
  87755. * Gets or sets a boolean which defines if optimization octree has to be updated
  87756. */
  87757. set: function (value) {
  87758. MergeMeshesOptimization._UpdateSelectionTree = value;
  87759. },
  87760. enumerable: true,
  87761. configurable: true
  87762. });
  87763. /**
  87764. * Gets a string describing the action executed by the current optimization
  87765. * @return description string
  87766. */
  87767. MergeMeshesOptimization.prototype.getDescription = function () {
  87768. return "Merging similar meshes together";
  87769. };
  87770. /**
  87771. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  87772. * @param scene defines the current scene where to apply this optimization
  87773. * @param optimizer defines the current optimizer
  87774. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  87775. * @returns true if everything that can be done was applied
  87776. */
  87777. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  87778. var globalPool = scene.meshes.slice(0);
  87779. var globalLength = globalPool.length;
  87780. for (var index = 0; index < globalLength; index++) {
  87781. var currentPool = new Array();
  87782. var current = globalPool[index];
  87783. // Checks
  87784. if (!this._canBeMerged(current)) {
  87785. continue;
  87786. }
  87787. currentPool.push(current);
  87788. // Find compatible meshes
  87789. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  87790. var otherMesh = globalPool[subIndex];
  87791. if (!this._canBeMerged(otherMesh)) {
  87792. continue;
  87793. }
  87794. if (otherMesh.material !== current.material) {
  87795. continue;
  87796. }
  87797. if (otherMesh.checkCollisions !== current.checkCollisions) {
  87798. continue;
  87799. }
  87800. currentPool.push(otherMesh);
  87801. globalLength--;
  87802. globalPool.splice(subIndex, 1);
  87803. subIndex--;
  87804. }
  87805. if (currentPool.length < 2) {
  87806. continue;
  87807. }
  87808. // Merge meshes
  87809. BABYLON.Mesh.MergeMeshes(currentPool);
  87810. }
  87811. if (updateSelectionTree != undefined) {
  87812. if (updateSelectionTree) {
  87813. scene.createOrUpdateSelectionOctree();
  87814. }
  87815. }
  87816. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  87817. scene.createOrUpdateSelectionOctree();
  87818. }
  87819. return true;
  87820. };
  87821. ;
  87822. MergeMeshesOptimization._UpdateSelectionTree = false;
  87823. return MergeMeshesOptimization;
  87824. }(SceneOptimization));
  87825. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  87826. /**
  87827. * Defines a list of options used by SceneOptimizer
  87828. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  87829. */
  87830. var SceneOptimizerOptions = /** @class */ (function () {
  87831. /**
  87832. * Creates a new list of options used by SceneOptimizer
  87833. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  87834. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  87835. */
  87836. function SceneOptimizerOptions(
  87837. /**
  87838. * Defines the target frame rate to reach (60 by default)
  87839. */
  87840. targetFrameRate,
  87841. /**
  87842. * Defines the interval between two checkes (2000ms by default)
  87843. */
  87844. trackerDuration) {
  87845. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  87846. if (trackerDuration === void 0) { trackerDuration = 2000; }
  87847. this.targetFrameRate = targetFrameRate;
  87848. this.trackerDuration = trackerDuration;
  87849. /**
  87850. * Gets the list of optimizations to apply
  87851. */
  87852. this.optimizations = new Array();
  87853. }
  87854. /**
  87855. * Add a new optimization
  87856. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  87857. * @returns the current SceneOptimizerOptions
  87858. */
  87859. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  87860. this.optimizations.push(optimization);
  87861. return this;
  87862. };
  87863. /**
  87864. * Add a new custom optimization
  87865. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  87866. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  87867. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  87868. * @returns the current SceneOptimizerOptions
  87869. */
  87870. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  87871. if (priority === void 0) { priority = 0; }
  87872. var optimization = new CustomOptimization(priority);
  87873. optimization.onApply = onApply;
  87874. optimization.onGetDescription = onGetDescription;
  87875. this.optimizations.push(optimization);
  87876. return this;
  87877. };
  87878. /**
  87879. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  87880. * @param targetFrameRate defines the target frame rate (60 by default)
  87881. * @returns a SceneOptimizerOptions object
  87882. */
  87883. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  87884. var result = new SceneOptimizerOptions(targetFrameRate);
  87885. var priority = 0;
  87886. result.addOptimization(new MergeMeshesOptimization(priority));
  87887. result.addOptimization(new ShadowsOptimization(priority));
  87888. result.addOptimization(new LensFlaresOptimization(priority));
  87889. // Next priority
  87890. priority++;
  87891. result.addOptimization(new PostProcessesOptimization(priority));
  87892. result.addOptimization(new ParticlesOptimization(priority));
  87893. // Next priority
  87894. priority++;
  87895. result.addOptimization(new TextureOptimization(priority, 1024));
  87896. return result;
  87897. };
  87898. /**
  87899. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  87900. * @param targetFrameRate defines the target frame rate (60 by default)
  87901. * @returns a SceneOptimizerOptions object
  87902. */
  87903. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  87904. var result = new SceneOptimizerOptions(targetFrameRate);
  87905. var priority = 0;
  87906. result.addOptimization(new MergeMeshesOptimization(priority));
  87907. result.addOptimization(new ShadowsOptimization(priority));
  87908. result.addOptimization(new LensFlaresOptimization(priority));
  87909. // Next priority
  87910. priority++;
  87911. result.addOptimization(new PostProcessesOptimization(priority));
  87912. result.addOptimization(new ParticlesOptimization(priority));
  87913. // Next priority
  87914. priority++;
  87915. result.addOptimization(new TextureOptimization(priority, 512));
  87916. // Next priority
  87917. priority++;
  87918. result.addOptimization(new RenderTargetsOptimization(priority));
  87919. // Next priority
  87920. priority++;
  87921. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  87922. return result;
  87923. };
  87924. /**
  87925. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  87926. * @param targetFrameRate defines the target frame rate (60 by default)
  87927. * @returns a SceneOptimizerOptions object
  87928. */
  87929. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  87930. var result = new SceneOptimizerOptions(targetFrameRate);
  87931. var priority = 0;
  87932. result.addOptimization(new MergeMeshesOptimization(priority));
  87933. result.addOptimization(new ShadowsOptimization(priority));
  87934. result.addOptimization(new LensFlaresOptimization(priority));
  87935. // Next priority
  87936. priority++;
  87937. result.addOptimization(new PostProcessesOptimization(priority));
  87938. result.addOptimization(new ParticlesOptimization(priority));
  87939. // Next priority
  87940. priority++;
  87941. result.addOptimization(new TextureOptimization(priority, 256));
  87942. // Next priority
  87943. priority++;
  87944. result.addOptimization(new RenderTargetsOptimization(priority));
  87945. // Next priority
  87946. priority++;
  87947. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  87948. return result;
  87949. };
  87950. return SceneOptimizerOptions;
  87951. }());
  87952. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  87953. /**
  87954. * Class used to run optimizations in order to reach a target frame rate
  87955. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  87956. */
  87957. var SceneOptimizer = /** @class */ (function () {
  87958. /**
  87959. * Creates a new SceneOptimizer
  87960. * @param scene defines the scene to work on
  87961. * @param options defines the options to use with the SceneOptimizer
  87962. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  87963. * @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)
  87964. */
  87965. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  87966. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  87967. if (improvementMode === void 0) { improvementMode = false; }
  87968. var _this = this;
  87969. this._isRunning = false;
  87970. this._currentPriorityLevel = 0;
  87971. this._targetFrameRate = 60;
  87972. this._trackerDuration = 2000;
  87973. this._currentFrameRate = 0;
  87974. this._improvementMode = false;
  87975. /**
  87976. * Defines an observable called when the optimizer reaches the target frame rate
  87977. */
  87978. this.onSuccessObservable = new BABYLON.Observable();
  87979. /**
  87980. * Defines an observable called when the optimizer enables an optimization
  87981. */
  87982. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  87983. /**
  87984. * Defines an observable called when the optimizer is not able to reach the target frame rate
  87985. */
  87986. this.onFailureObservable = new BABYLON.Observable();
  87987. if (!options) {
  87988. this._options = new SceneOptimizerOptions();
  87989. }
  87990. else {
  87991. this._options = options;
  87992. }
  87993. if (this._options.targetFrameRate) {
  87994. this._targetFrameRate = this._options.targetFrameRate;
  87995. }
  87996. if (this._options.trackerDuration) {
  87997. this._trackerDuration = this._options.trackerDuration;
  87998. }
  87999. if (autoGeneratePriorities) {
  88000. var priority = 0;
  88001. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  88002. var optim = _a[_i];
  88003. optim.priority = priority++;
  88004. }
  88005. }
  88006. this._improvementMode = improvementMode;
  88007. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  88008. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  88009. _this._sceneDisposeObserver = null;
  88010. _this.dispose();
  88011. });
  88012. }
  88013. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  88014. /**
  88015. * Gets a boolean indicating if the optimizer is in improvement mode
  88016. */
  88017. get: function () {
  88018. return this._improvementMode;
  88019. },
  88020. enumerable: true,
  88021. configurable: true
  88022. });
  88023. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  88024. /**
  88025. * Gets the current priority level (0 at start)
  88026. */
  88027. get: function () {
  88028. return this._currentPriorityLevel;
  88029. },
  88030. enumerable: true,
  88031. configurable: true
  88032. });
  88033. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  88034. /**
  88035. * Gets the current frame rate checked by the SceneOptimizer
  88036. */
  88037. get: function () {
  88038. return this._currentFrameRate;
  88039. },
  88040. enumerable: true,
  88041. configurable: true
  88042. });
  88043. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  88044. /**
  88045. * Gets or sets the current target frame rate (60 by default)
  88046. */
  88047. get: function () {
  88048. return this._targetFrameRate;
  88049. },
  88050. /**
  88051. * Gets or sets the current target frame rate (60 by default)
  88052. */
  88053. set: function (value) {
  88054. this._targetFrameRate = value;
  88055. },
  88056. enumerable: true,
  88057. configurable: true
  88058. });
  88059. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  88060. /**
  88061. * Gets or sets the current interval between two checks (every 2000ms by default)
  88062. */
  88063. get: function () {
  88064. return this._trackerDuration;
  88065. },
  88066. /**
  88067. * Gets or sets the current interval between two checks (every 2000ms by default)
  88068. */
  88069. set: function (value) {
  88070. this._trackerDuration = value;
  88071. },
  88072. enumerable: true,
  88073. configurable: true
  88074. });
  88075. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  88076. /**
  88077. * Gets the list of active optimizations
  88078. */
  88079. get: function () {
  88080. return this._options.optimizations;
  88081. },
  88082. enumerable: true,
  88083. configurable: true
  88084. });
  88085. /**
  88086. * Stops the current optimizer
  88087. */
  88088. SceneOptimizer.prototype.stop = function () {
  88089. this._isRunning = false;
  88090. };
  88091. /**
  88092. * Reset the optimizer to initial step (current priority level = 0)
  88093. */
  88094. SceneOptimizer.prototype.reset = function () {
  88095. this._currentPriorityLevel = 0;
  88096. };
  88097. /**
  88098. * Start the optimizer. By default it will try to reach a specific framerate
  88099. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  88100. */
  88101. SceneOptimizer.prototype.start = function () {
  88102. var _this = this;
  88103. if (this._isRunning) {
  88104. return;
  88105. }
  88106. this._isRunning = true;
  88107. // Let's wait for the scene to be ready before running our check
  88108. this._scene.executeWhenReady(function () {
  88109. setTimeout(function () {
  88110. _this._checkCurrentState();
  88111. }, _this._trackerDuration);
  88112. });
  88113. };
  88114. SceneOptimizer.prototype._checkCurrentState = function () {
  88115. var _this = this;
  88116. if (!this._isRunning) {
  88117. return;
  88118. }
  88119. var scene = this._scene;
  88120. var options = this._options;
  88121. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  88122. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  88123. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  88124. this._isRunning = false;
  88125. this.onSuccessObservable.notifyObservers(this);
  88126. return;
  88127. }
  88128. // Apply current level of optimizations
  88129. var allDone = true;
  88130. var noOptimizationApplied = true;
  88131. for (var index = 0; index < options.optimizations.length; index++) {
  88132. var optimization = options.optimizations[index];
  88133. if (optimization.priority === this._currentPriorityLevel) {
  88134. noOptimizationApplied = false;
  88135. allDone = allDone && optimization.apply(scene, this);
  88136. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  88137. }
  88138. }
  88139. // If no optimization was applied, this is a failure :(
  88140. if (noOptimizationApplied) {
  88141. this._isRunning = false;
  88142. this.onFailureObservable.notifyObservers(this);
  88143. return;
  88144. }
  88145. // If all optimizations were done, move to next level
  88146. if (allDone) {
  88147. this._currentPriorityLevel++;
  88148. }
  88149. // Let's the system running for a specific amount of time before checking FPS
  88150. scene.executeWhenReady(function () {
  88151. setTimeout(function () {
  88152. _this._checkCurrentState();
  88153. }, _this._trackerDuration);
  88154. });
  88155. };
  88156. /**
  88157. * Release all resources
  88158. */
  88159. SceneOptimizer.prototype.dispose = function () {
  88160. this.stop();
  88161. this.onSuccessObservable.clear();
  88162. this.onFailureObservable.clear();
  88163. this.onNewOptimizationAppliedObservable.clear();
  88164. if (this._sceneDisposeObserver) {
  88165. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  88166. }
  88167. };
  88168. /**
  88169. * Helper function to create a SceneOptimizer with one single line of code
  88170. * @param scene defines the scene to work on
  88171. * @param options defines the options to use with the SceneOptimizer
  88172. * @param onSuccess defines a callback to call on success
  88173. * @param onFailure defines a callback to call on failure
  88174. * @returns the new SceneOptimizer object
  88175. */
  88176. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  88177. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  88178. if (onSuccess) {
  88179. optimizer.onSuccessObservable.add(function () {
  88180. onSuccess();
  88181. });
  88182. }
  88183. if (onFailure) {
  88184. optimizer.onFailureObservable.add(function () {
  88185. onFailure();
  88186. });
  88187. }
  88188. optimizer.start();
  88189. return optimizer;
  88190. };
  88191. return SceneOptimizer;
  88192. }());
  88193. BABYLON.SceneOptimizer = SceneOptimizer;
  88194. })(BABYLON || (BABYLON = {}));
  88195. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  88196. "use strict";
  88197. var BABYLON;
  88198. (function (BABYLON) {
  88199. var OutlineRenderer = /** @class */ (function () {
  88200. function OutlineRenderer(scene) {
  88201. this.zOffset = 1;
  88202. this._scene = scene;
  88203. }
  88204. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  88205. var _this = this;
  88206. if (useOverlay === void 0) { useOverlay = false; }
  88207. var scene = this._scene;
  88208. var engine = this._scene.getEngine();
  88209. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  88210. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  88211. return;
  88212. }
  88213. var mesh = subMesh.getRenderingMesh();
  88214. var material = subMesh.getMaterial();
  88215. if (!material || !scene.activeCamera) {
  88216. return;
  88217. }
  88218. engine.enableEffect(this._effect);
  88219. // Logarithmic depth
  88220. if (material.useLogarithmicDepth) {
  88221. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  88222. }
  88223. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  88224. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  88225. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  88226. // Bones
  88227. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  88228. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  88229. }
  88230. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  88231. // Alpha test
  88232. if (material && material.needAlphaTesting()) {
  88233. var alphaTexture = material.getAlphaTestTexture();
  88234. if (alphaTexture) {
  88235. this._effect.setTexture("diffuseSampler", alphaTexture);
  88236. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  88237. }
  88238. }
  88239. engine.setZOffset(-this.zOffset);
  88240. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  88241. engine.setZOffset(0);
  88242. };
  88243. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  88244. var defines = [];
  88245. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  88246. var mesh = subMesh.getMesh();
  88247. var material = subMesh.getMaterial();
  88248. if (material) {
  88249. // Alpha test
  88250. if (material.needAlphaTesting()) {
  88251. defines.push("#define ALPHATEST");
  88252. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  88253. attribs.push(BABYLON.VertexBuffer.UVKind);
  88254. defines.push("#define UV1");
  88255. }
  88256. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  88257. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  88258. defines.push("#define UV2");
  88259. }
  88260. }
  88261. //Logarithmic depth
  88262. if (material.useLogarithmicDepth) {
  88263. defines.push("#define LOGARITHMICDEPTH");
  88264. }
  88265. }
  88266. // Bones
  88267. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  88268. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  88269. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  88270. if (mesh.numBoneInfluencers > 4) {
  88271. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  88272. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  88273. }
  88274. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  88275. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  88276. }
  88277. else {
  88278. defines.push("#define NUM_BONE_INFLUENCERS 0");
  88279. }
  88280. // Instances
  88281. if (useInstances) {
  88282. defines.push("#define INSTANCES");
  88283. attribs.push("world0");
  88284. attribs.push("world1");
  88285. attribs.push("world2");
  88286. attribs.push("world3");
  88287. }
  88288. // Get correct effect
  88289. var join = defines.join("\n");
  88290. if (this._cachedDefines !== join) {
  88291. this._cachedDefines = join;
  88292. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  88293. }
  88294. return this._effect.isReady();
  88295. };
  88296. return OutlineRenderer;
  88297. }());
  88298. BABYLON.OutlineRenderer = OutlineRenderer;
  88299. })(BABYLON || (BABYLON = {}));
  88300. //# sourceMappingURL=babylon.outlineRenderer.js.map
  88301. "use strict";
  88302. var BABYLON;
  88303. (function (BABYLON) {
  88304. var FaceAdjacencies = /** @class */ (function () {
  88305. function FaceAdjacencies() {
  88306. this.edges = new Array();
  88307. this.edgesConnectedCount = 0;
  88308. }
  88309. return FaceAdjacencies;
  88310. }());
  88311. var EdgesRenderer = /** @class */ (function () {
  88312. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  88313. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  88314. if (epsilon === void 0) { epsilon = 0.95; }
  88315. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  88316. this.edgesWidthScalerForOrthographic = 1000.0;
  88317. this.edgesWidthScalerForPerspective = 50.0;
  88318. this._linesPositions = new Array();
  88319. this._linesNormals = new Array();
  88320. this._linesIndices = new Array();
  88321. this._buffers = {};
  88322. this._checkVerticesInsteadOfIndices = false;
  88323. this._source = source;
  88324. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  88325. this._epsilon = epsilon;
  88326. this._prepareRessources();
  88327. this._generateEdgesLines();
  88328. }
  88329. EdgesRenderer.prototype._prepareRessources = function () {
  88330. if (this._lineShader) {
  88331. return;
  88332. }
  88333. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  88334. attributes: ["position", "normal"],
  88335. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  88336. });
  88337. this._lineShader.disableDepthWrite = true;
  88338. this._lineShader.backFaceCulling = false;
  88339. };
  88340. EdgesRenderer.prototype._rebuild = function () {
  88341. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  88342. if (buffer) {
  88343. buffer._rebuild();
  88344. }
  88345. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  88346. if (buffer) {
  88347. buffer._rebuild();
  88348. }
  88349. var scene = this._source.getScene();
  88350. var engine = scene.getEngine();
  88351. this._ib = engine.createIndexBuffer(this._linesIndices);
  88352. };
  88353. EdgesRenderer.prototype.dispose = function () {
  88354. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  88355. if (buffer) {
  88356. buffer.dispose();
  88357. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  88358. }
  88359. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  88360. if (buffer) {
  88361. buffer.dispose();
  88362. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  88363. }
  88364. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  88365. this._lineShader.dispose();
  88366. };
  88367. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  88368. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  88369. return 0;
  88370. }
  88371. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  88372. return 1;
  88373. }
  88374. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  88375. return 2;
  88376. }
  88377. return -1;
  88378. };
  88379. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  88380. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  88381. return 0;
  88382. }
  88383. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  88384. return 1;
  88385. }
  88386. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  88387. return 2;
  88388. }
  88389. return -1;
  88390. };
  88391. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  88392. var needToCreateLine;
  88393. if (edge === undefined) {
  88394. needToCreateLine = true;
  88395. }
  88396. else {
  88397. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  88398. needToCreateLine = dotProduct < this._epsilon;
  88399. }
  88400. if (needToCreateLine) {
  88401. var offset = this._linesPositions.length / 3;
  88402. var normal = p0.subtract(p1);
  88403. normal.normalize();
  88404. // Positions
  88405. this._linesPositions.push(p0.x);
  88406. this._linesPositions.push(p0.y);
  88407. this._linesPositions.push(p0.z);
  88408. this._linesPositions.push(p0.x);
  88409. this._linesPositions.push(p0.y);
  88410. this._linesPositions.push(p0.z);
  88411. this._linesPositions.push(p1.x);
  88412. this._linesPositions.push(p1.y);
  88413. this._linesPositions.push(p1.z);
  88414. this._linesPositions.push(p1.x);
  88415. this._linesPositions.push(p1.y);
  88416. this._linesPositions.push(p1.z);
  88417. // Normals
  88418. this._linesNormals.push(p1.x);
  88419. this._linesNormals.push(p1.y);
  88420. this._linesNormals.push(p1.z);
  88421. this._linesNormals.push(-1);
  88422. this._linesNormals.push(p1.x);
  88423. this._linesNormals.push(p1.y);
  88424. this._linesNormals.push(p1.z);
  88425. this._linesNormals.push(1);
  88426. this._linesNormals.push(p0.x);
  88427. this._linesNormals.push(p0.y);
  88428. this._linesNormals.push(p0.z);
  88429. this._linesNormals.push(-1);
  88430. this._linesNormals.push(p0.x);
  88431. this._linesNormals.push(p0.y);
  88432. this._linesNormals.push(p0.z);
  88433. this._linesNormals.push(1);
  88434. // Indices
  88435. this._linesIndices.push(offset);
  88436. this._linesIndices.push(offset + 1);
  88437. this._linesIndices.push(offset + 2);
  88438. this._linesIndices.push(offset);
  88439. this._linesIndices.push(offset + 2);
  88440. this._linesIndices.push(offset + 3);
  88441. }
  88442. };
  88443. EdgesRenderer.prototype._generateEdgesLines = function () {
  88444. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  88445. var indices = this._source.getIndices();
  88446. if (!indices || !positions) {
  88447. return;
  88448. }
  88449. // First let's find adjacencies
  88450. var adjacencies = new Array();
  88451. var faceNormals = new Array();
  88452. var index;
  88453. var faceAdjacencies;
  88454. // Prepare faces
  88455. for (index = 0; index < indices.length; index += 3) {
  88456. faceAdjacencies = new FaceAdjacencies();
  88457. var p0Index = indices[index];
  88458. var p1Index = indices[index + 1];
  88459. var p2Index = indices[index + 2];
  88460. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  88461. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  88462. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  88463. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  88464. faceNormal.normalize();
  88465. faceNormals.push(faceNormal);
  88466. adjacencies.push(faceAdjacencies);
  88467. }
  88468. // Scan
  88469. for (index = 0; index < adjacencies.length; index++) {
  88470. faceAdjacencies = adjacencies[index];
  88471. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  88472. var otherFaceAdjacencies = adjacencies[otherIndex];
  88473. if (faceAdjacencies.edgesConnectedCount === 3) {
  88474. break;
  88475. }
  88476. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  88477. continue;
  88478. }
  88479. var otherP0 = indices[otherIndex * 3];
  88480. var otherP1 = indices[otherIndex * 3 + 1];
  88481. var otherP2 = indices[otherIndex * 3 + 2];
  88482. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  88483. var otherEdgeIndex = 0;
  88484. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  88485. continue;
  88486. }
  88487. switch (edgeIndex) {
  88488. case 0:
  88489. if (this._checkVerticesInsteadOfIndices) {
  88490. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  88491. }
  88492. else {
  88493. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  88494. }
  88495. break;
  88496. case 1:
  88497. if (this._checkVerticesInsteadOfIndices) {
  88498. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  88499. }
  88500. else {
  88501. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  88502. }
  88503. break;
  88504. case 2:
  88505. if (this._checkVerticesInsteadOfIndices) {
  88506. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  88507. }
  88508. else {
  88509. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  88510. }
  88511. break;
  88512. }
  88513. if (otherEdgeIndex === -1) {
  88514. continue;
  88515. }
  88516. faceAdjacencies.edges[edgeIndex] = otherIndex;
  88517. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  88518. faceAdjacencies.edgesConnectedCount++;
  88519. otherFaceAdjacencies.edgesConnectedCount++;
  88520. if (faceAdjacencies.edgesConnectedCount === 3) {
  88521. break;
  88522. }
  88523. }
  88524. }
  88525. }
  88526. // Create lines
  88527. for (index = 0; index < adjacencies.length; index++) {
  88528. // 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
  88529. var current = adjacencies[index];
  88530. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  88531. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  88532. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  88533. }
  88534. // Merge into a single mesh
  88535. var engine = this._source.getScene().getEngine();
  88536. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  88537. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  88538. this._ib = engine.createIndexBuffer(this._linesIndices);
  88539. this._indicesCount = this._linesIndices.length;
  88540. };
  88541. EdgesRenderer.prototype.render = function () {
  88542. var scene = this._source.getScene();
  88543. if (!this._lineShader.isReady() || !scene.activeCamera) {
  88544. return;
  88545. }
  88546. var engine = scene.getEngine();
  88547. this._lineShader._preBind();
  88548. // VBOs
  88549. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  88550. scene.resetCachedMaterial();
  88551. this._lineShader.setColor4("color", this._source.edgesColor);
  88552. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  88553. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  88554. }
  88555. else {
  88556. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  88557. }
  88558. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  88559. this._lineShader.bind(this._source.getWorldMatrix());
  88560. // Draw order
  88561. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  88562. this._lineShader.unbind();
  88563. engine.setDepthWrite(true);
  88564. };
  88565. return EdgesRenderer;
  88566. }());
  88567. BABYLON.EdgesRenderer = EdgesRenderer;
  88568. })(BABYLON || (BABYLON = {}));
  88569. //# sourceMappingURL=babylon.edgesRenderer.js.map
  88570. "use strict";
  88571. var __assign = (this && this.__assign) || Object.assign || function(t) {
  88572. for (var s, i = 1, n = arguments.length; i < n; i++) {
  88573. s = arguments[i];
  88574. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  88575. t[p] = s[p];
  88576. }
  88577. return t;
  88578. };
  88579. var BABYLON;
  88580. (function (BABYLON) {
  88581. /**
  88582. * The effect layer Helps adding post process effect blended with the main pass.
  88583. *
  88584. * This can be for instance use to generate glow or higlight effects on the scene.
  88585. *
  88586. * The effect layer class can not be used directly and is intented to inherited from to be
  88587. * customized per effects.
  88588. */
  88589. var EffectLayer = /** @class */ (function () {
  88590. /**
  88591. * Instantiates a new effect Layer and references it in the scene.
  88592. * @param name The name of the layer
  88593. * @param scene The scene to use the layer in
  88594. */
  88595. function EffectLayer(
  88596. /** The Friendly of the effect in the scene */
  88597. name, scene) {
  88598. this._vertexBuffers = {};
  88599. this._maxSize = 0;
  88600. this._mainTextureDesiredSize = { width: 0, height: 0 };
  88601. this._shouldRender = true;
  88602. this._postProcesses = [];
  88603. this._textures = [];
  88604. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  88605. /**
  88606. * The clear color of the texture used to generate the glow map.
  88607. */
  88608. this.neutralColor = new BABYLON.Color4();
  88609. /**
  88610. * Specifies wether the highlight layer is enabled or not.
  88611. */
  88612. this.isEnabled = true;
  88613. /**
  88614. * An event triggered when the effect layer has been disposed.
  88615. */
  88616. this.onDisposeObservable = new BABYLON.Observable();
  88617. /**
  88618. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  88619. */
  88620. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  88621. /**
  88622. * An event triggered when the generated texture is being merged in the scene.
  88623. */
  88624. this.onBeforeComposeObservable = new BABYLON.Observable();
  88625. /**
  88626. * An event triggered when the generated texture has been merged in the scene.
  88627. */
  88628. this.onAfterComposeObservable = new BABYLON.Observable();
  88629. /**
  88630. * An event triggered when the efffect layer changes its size.
  88631. */
  88632. this.onSizeChangedObservable = new BABYLON.Observable();
  88633. this.name = name;
  88634. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  88635. this._engine = scene.getEngine();
  88636. this._maxSize = this._engine.getCaps().maxTextureSize;
  88637. this._scene.effectLayers.push(this);
  88638. // Generate Buffers
  88639. this._generateIndexBuffer();
  88640. this._genrateVertexBuffer();
  88641. }
  88642. Object.defineProperty(EffectLayer.prototype, "camera", {
  88643. /**
  88644. * Gets the camera attached to the layer.
  88645. */
  88646. get: function () {
  88647. return this._effectLayerOptions.camera;
  88648. },
  88649. enumerable: true,
  88650. configurable: true
  88651. });
  88652. /**
  88653. * Initializes the effect layer with the required options.
  88654. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  88655. */
  88656. EffectLayer.prototype._init = function (options) {
  88657. // Adapt options
  88658. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  88659. this._setMainTextureSize();
  88660. this._createMainTexture();
  88661. this._createTextureAndPostProcesses();
  88662. this._mergeEffect = this._createMergeEffect();
  88663. };
  88664. /**
  88665. * Generates the index buffer of the full screen quad blending to the main canvas.
  88666. */
  88667. EffectLayer.prototype._generateIndexBuffer = function () {
  88668. // Indices
  88669. var indices = [];
  88670. indices.push(0);
  88671. indices.push(1);
  88672. indices.push(2);
  88673. indices.push(0);
  88674. indices.push(2);
  88675. indices.push(3);
  88676. this._indexBuffer = this._engine.createIndexBuffer(indices);
  88677. };
  88678. /**
  88679. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  88680. */
  88681. EffectLayer.prototype._genrateVertexBuffer = function () {
  88682. // VBO
  88683. var vertices = [];
  88684. vertices.push(1, 1);
  88685. vertices.push(-1, 1);
  88686. vertices.push(-1, -1);
  88687. vertices.push(1, -1);
  88688. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  88689. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  88690. };
  88691. /**
  88692. * Sets the main texture desired size which is the closest power of two
  88693. * of the engine canvas size.
  88694. */
  88695. EffectLayer.prototype._setMainTextureSize = function () {
  88696. if (this._effectLayerOptions.mainTextureFixedSize) {
  88697. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  88698. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  88699. }
  88700. else {
  88701. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  88702. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  88703. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  88704. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  88705. }
  88706. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  88707. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  88708. };
  88709. /**
  88710. * Creates the main texture for the effect layer.
  88711. */
  88712. EffectLayer.prototype._createMainTexture = function () {
  88713. var _this = this;
  88714. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  88715. width: this._mainTextureDesiredSize.width,
  88716. height: this._mainTextureDesiredSize.height
  88717. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  88718. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  88719. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88720. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88721. this._mainTexture.anisotropicFilteringLevel = 1;
  88722. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  88723. this._mainTexture.renderParticles = false;
  88724. this._mainTexture.renderList = null;
  88725. this._mainTexture.ignoreCameraViewport = true;
  88726. // Custom render function
  88727. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  88728. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  88729. var index;
  88730. var engine = _this._scene.getEngine();
  88731. if (depthOnlySubMeshes.length) {
  88732. engine.setColorWrite(false);
  88733. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  88734. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  88735. }
  88736. engine.setColorWrite(true);
  88737. }
  88738. for (index = 0; index < opaqueSubMeshes.length; index++) {
  88739. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  88740. }
  88741. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  88742. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  88743. }
  88744. for (index = 0; index < transparentSubMeshes.length; index++) {
  88745. _this._renderSubMesh(transparentSubMeshes.data[index]);
  88746. }
  88747. };
  88748. this._mainTexture.onClearObservable.add(function (engine) {
  88749. engine.clear(_this.neutralColor, true, true, true);
  88750. });
  88751. };
  88752. /**
  88753. * Checks for the readiness of the element composing the layer.
  88754. * @param subMesh the mesh to check for
  88755. * @param useInstances specify wether or not to use instances to render the mesh
  88756. * @param emissiveTexture the associated emissive texture used to generate the glow
  88757. * @return true if ready otherwise, false
  88758. */
  88759. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  88760. var material = subMesh.getMaterial();
  88761. if (!material) {
  88762. return false;
  88763. }
  88764. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  88765. return false;
  88766. }
  88767. var defines = [];
  88768. var attribs = [BABYLON.VertexBuffer.PositionKind];
  88769. var mesh = subMesh.getMesh();
  88770. var uv1 = false;
  88771. var uv2 = false;
  88772. // Alpha test
  88773. if (material && material.needAlphaTesting()) {
  88774. var alphaTexture = material.getAlphaTestTexture();
  88775. if (alphaTexture) {
  88776. defines.push("#define ALPHATEST");
  88777. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  88778. alphaTexture.coordinatesIndex === 1) {
  88779. defines.push("#define DIFFUSEUV2");
  88780. uv2 = true;
  88781. }
  88782. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  88783. defines.push("#define DIFFUSEUV1");
  88784. uv1 = true;
  88785. }
  88786. }
  88787. }
  88788. // Emissive
  88789. if (emissiveTexture) {
  88790. defines.push("#define EMISSIVE");
  88791. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  88792. emissiveTexture.coordinatesIndex === 1) {
  88793. defines.push("#define EMISSIVEUV2");
  88794. uv2 = true;
  88795. }
  88796. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  88797. defines.push("#define EMISSIVEUV1");
  88798. uv1 = true;
  88799. }
  88800. }
  88801. if (uv1) {
  88802. attribs.push(BABYLON.VertexBuffer.UVKind);
  88803. defines.push("#define UV1");
  88804. }
  88805. if (uv2) {
  88806. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  88807. defines.push("#define UV2");
  88808. }
  88809. // Bones
  88810. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  88811. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  88812. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  88813. if (mesh.numBoneInfluencers > 4) {
  88814. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  88815. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  88816. }
  88817. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  88818. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  88819. }
  88820. else {
  88821. defines.push("#define NUM_BONE_INFLUENCERS 0");
  88822. }
  88823. // Morph targets
  88824. var manager = mesh.morphTargetManager;
  88825. var morphInfluencers = 0;
  88826. if (manager) {
  88827. if (manager.numInfluencers > 0) {
  88828. defines.push("#define MORPHTARGETS");
  88829. morphInfluencers = manager.numInfluencers;
  88830. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  88831. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  88832. }
  88833. }
  88834. // Instances
  88835. if (useInstances) {
  88836. defines.push("#define INSTANCES");
  88837. attribs.push("world0");
  88838. attribs.push("world1");
  88839. attribs.push("world2");
  88840. attribs.push("world3");
  88841. }
  88842. // Get correct effect
  88843. var join = defines.join("\n");
  88844. if (this._cachedDefines !== join) {
  88845. this._cachedDefines = join;
  88846. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  88847. }
  88848. return this._effectLayerMapGenerationEffect.isReady();
  88849. };
  88850. /**
  88851. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  88852. */
  88853. EffectLayer.prototype.render = function () {
  88854. var currentEffect = this._mergeEffect;
  88855. // Check
  88856. if (!currentEffect.isReady())
  88857. return;
  88858. for (var i = 0; i < this._postProcesses.length; i++) {
  88859. if (!this._postProcesses[i].isReady()) {
  88860. return;
  88861. }
  88862. }
  88863. var engine = this._scene.getEngine();
  88864. this.onBeforeComposeObservable.notifyObservers(this);
  88865. // Render
  88866. engine.enableEffect(currentEffect);
  88867. engine.setState(false);
  88868. // VBOs
  88869. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  88870. // Cache
  88871. var previousAlphaMode = engine.getAlphaMode();
  88872. // Go Blend.
  88873. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  88874. // Blends the map on the main canvas.
  88875. this._internalRender(currentEffect);
  88876. // Restore Alpha
  88877. engine.setAlphaMode(previousAlphaMode);
  88878. this.onAfterComposeObservable.notifyObservers(this);
  88879. // Handle size changes.
  88880. var size = this._mainTexture.getSize();
  88881. this._setMainTextureSize();
  88882. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  88883. // Recreate RTT and post processes on size change.
  88884. this.onSizeChangedObservable.notifyObservers(this);
  88885. this._disposeTextureAndPostProcesses();
  88886. this._createMainTexture();
  88887. this._createTextureAndPostProcesses();
  88888. }
  88889. };
  88890. /**
  88891. * Determine if a given mesh will be used in the current effect.
  88892. * @param mesh mesh to test
  88893. * @returns true if the mesh will be used
  88894. */
  88895. EffectLayer.prototype.hasMesh = function (mesh) {
  88896. return true;
  88897. };
  88898. /**
  88899. * Returns true if the layer contains information to display, otherwise false.
  88900. * @returns true if the glow layer should be rendered
  88901. */
  88902. EffectLayer.prototype.shouldRender = function () {
  88903. return this.isEnabled && this._shouldRender;
  88904. };
  88905. /**
  88906. * Returns true if the mesh should render, otherwise false.
  88907. * @param mesh The mesh to render
  88908. * @returns true if it should render otherwise false
  88909. */
  88910. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  88911. return true;
  88912. };
  88913. /**
  88914. * Returns true if the mesh should render, otherwise false.
  88915. * @param mesh The mesh to render
  88916. * @returns true if it should render otherwise false
  88917. */
  88918. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  88919. return true;
  88920. };
  88921. /**
  88922. * Renders the submesh passed in parameter to the generation map.
  88923. */
  88924. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  88925. var _this = this;
  88926. if (!this.shouldRender()) {
  88927. return;
  88928. }
  88929. var material = subMesh.getMaterial();
  88930. var mesh = subMesh.getRenderingMesh();
  88931. var scene = this._scene;
  88932. var engine = scene.getEngine();
  88933. if (!material) {
  88934. return;
  88935. }
  88936. // Do not block in blend mode.
  88937. if (material.needAlphaBlendingForMesh(mesh)) {
  88938. return;
  88939. }
  88940. // Culling
  88941. engine.setState(material.backFaceCulling);
  88942. // Managing instances
  88943. var batch = mesh._getInstancesRenderList(subMesh._id);
  88944. if (batch.mustReturn) {
  88945. return;
  88946. }
  88947. // Early Exit per mesh
  88948. if (!this._shouldRenderMesh(mesh)) {
  88949. return;
  88950. }
  88951. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  88952. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  88953. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  88954. engine.enableEffect(this._effectLayerMapGenerationEffect);
  88955. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  88956. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  88957. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  88958. // Alpha test
  88959. if (material && material.needAlphaTesting()) {
  88960. var alphaTexture = material.getAlphaTestTexture();
  88961. if (alphaTexture) {
  88962. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  88963. var textureMatrix = alphaTexture.getTextureMatrix();
  88964. if (textureMatrix) {
  88965. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  88966. }
  88967. }
  88968. }
  88969. // Glow emissive only
  88970. if (this._emissiveTextureAndColor.texture) {
  88971. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  88972. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  88973. }
  88974. // Bones
  88975. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  88976. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  88977. }
  88978. // Morph targets
  88979. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  88980. // Draw
  88981. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  88982. }
  88983. else {
  88984. // Need to reset refresh rate of the shadowMap
  88985. this._mainTexture.resetRefreshCounter();
  88986. }
  88987. };
  88988. /**
  88989. * Rebuild the required buffers.
  88990. * @ignore Internal use only.
  88991. */
  88992. EffectLayer.prototype._rebuild = function () {
  88993. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88994. if (vb) {
  88995. vb._rebuild();
  88996. }
  88997. this._generateIndexBuffer();
  88998. };
  88999. /**
  89000. * Dispose only the render target textures and post process.
  89001. */
  89002. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  89003. this._mainTexture.dispose();
  89004. for (var i = 0; i < this._postProcesses.length; i++) {
  89005. if (this._postProcesses[i]) {
  89006. this._postProcesses[i].dispose();
  89007. }
  89008. }
  89009. this._postProcesses = [];
  89010. for (var i = 0; i < this._textures.length; i++) {
  89011. if (this._textures[i]) {
  89012. this._textures[i].dispose();
  89013. }
  89014. }
  89015. this._textures = [];
  89016. };
  89017. /**
  89018. * Dispose the highlight layer and free resources.
  89019. */
  89020. EffectLayer.prototype.dispose = function () {
  89021. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  89022. if (vertexBuffer) {
  89023. vertexBuffer.dispose();
  89024. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  89025. }
  89026. if (this._indexBuffer) {
  89027. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  89028. this._indexBuffer = null;
  89029. }
  89030. // Clean textures and post processes
  89031. this._disposeTextureAndPostProcesses();
  89032. // Remove from scene
  89033. var index = this._scene.effectLayers.indexOf(this, 0);
  89034. if (index > -1) {
  89035. this._scene.effectLayers.splice(index, 1);
  89036. }
  89037. // Callback
  89038. this.onDisposeObservable.notifyObservers(this);
  89039. this.onDisposeObservable.clear();
  89040. this.onBeforeRenderMainTextureObservable.clear();
  89041. this.onBeforeComposeObservable.clear();
  89042. this.onAfterComposeObservable.clear();
  89043. this.onSizeChangedObservable.clear();
  89044. };
  89045. /**
  89046. * Gets the class name of the effect layer
  89047. * @returns the string with the class name of the effect layer
  89048. */
  89049. EffectLayer.prototype.getClassName = function () {
  89050. return "EffectLayer";
  89051. };
  89052. __decorate([
  89053. BABYLON.serialize()
  89054. ], EffectLayer.prototype, "name", void 0);
  89055. __decorate([
  89056. BABYLON.serializeAsColor4()
  89057. ], EffectLayer.prototype, "neutralColor", void 0);
  89058. __decorate([
  89059. BABYLON.serialize()
  89060. ], EffectLayer.prototype, "isEnabled", void 0);
  89061. __decorate([
  89062. BABYLON.serializeAsCameraReference()
  89063. ], EffectLayer.prototype, "camera", null);
  89064. return EffectLayer;
  89065. }());
  89066. BABYLON.EffectLayer = EffectLayer;
  89067. })(BABYLON || (BABYLON = {}));
  89068. //# sourceMappingURL=babylon.effectLayer.js.map
  89069. "use strict";
  89070. var BABYLON;
  89071. (function (BABYLON) {
  89072. /**
  89073. * Special Glow Blur post process only blurring the alpha channel
  89074. * It enforces keeping the most luminous color in the color channel.
  89075. */
  89076. var GlowBlurPostProcess = /** @class */ (function (_super) {
  89077. __extends(GlowBlurPostProcess, _super);
  89078. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  89079. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  89080. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  89081. _this.direction = direction;
  89082. _this.kernel = kernel;
  89083. _this.onApplyObservable.add(function (effect) {
  89084. effect.setFloat2("screenSize", _this.width, _this.height);
  89085. effect.setVector2("direction", _this.direction);
  89086. effect.setFloat("blurWidth", _this.kernel);
  89087. });
  89088. return _this;
  89089. }
  89090. return GlowBlurPostProcess;
  89091. }(BABYLON.PostProcess));
  89092. /**
  89093. * The highlight layer Helps adding a glow effect around a mesh.
  89094. *
  89095. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  89096. * glowy meshes to your scene.
  89097. *
  89098. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  89099. */
  89100. var HighlightLayer = /** @class */ (function (_super) {
  89101. __extends(HighlightLayer, _super);
  89102. /**
  89103. * Instantiates a new highlight Layer and references it to the scene..
  89104. * @param name The name of the layer
  89105. * @param scene The scene to use the layer in
  89106. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  89107. */
  89108. function HighlightLayer(name, scene, options) {
  89109. var _this = _super.call(this, name, scene) || this;
  89110. _this.name = name;
  89111. /**
  89112. * Specifies whether or not the inner glow is ACTIVE in the layer.
  89113. */
  89114. _this.innerGlow = true;
  89115. /**
  89116. * Specifies whether or not the outer glow is ACTIVE in the layer.
  89117. */
  89118. _this.outerGlow = true;
  89119. /**
  89120. * An event triggered when the highlight layer is being blurred.
  89121. */
  89122. _this.onBeforeBlurObservable = new BABYLON.Observable();
  89123. /**
  89124. * An event triggered when the highlight layer has been blurred.
  89125. */
  89126. _this.onAfterBlurObservable = new BABYLON.Observable();
  89127. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  89128. _this._meshes = {};
  89129. _this._excludedMeshes = {};
  89130. _this.neutralColor = HighlightLayer.NeutralColor;
  89131. // Warn on stencil
  89132. if (!_this._engine.isStencilEnable) {
  89133. 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 }");
  89134. }
  89135. // Adapt options
  89136. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  89137. // Initialize the layer
  89138. _this._init({
  89139. alphaBlendingMode: _this._options.alphaBlendingMode,
  89140. camera: _this._options.camera,
  89141. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  89142. mainTextureRatio: _this._options.mainTextureRatio
  89143. });
  89144. // Do not render as long as no meshes have been added
  89145. _this._shouldRender = false;
  89146. return _this;
  89147. }
  89148. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  89149. /**
  89150. * Gets the horizontal size of the blur.
  89151. */
  89152. get: function () {
  89153. return this._horizontalBlurPostprocess.kernel;
  89154. },
  89155. /**
  89156. * Specifies the horizontal size of the blur.
  89157. */
  89158. set: function (value) {
  89159. this._horizontalBlurPostprocess.kernel = value;
  89160. },
  89161. enumerable: true,
  89162. configurable: true
  89163. });
  89164. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  89165. /**
  89166. * Gets the vertical size of the blur.
  89167. */
  89168. get: function () {
  89169. return this._verticalBlurPostprocess.kernel;
  89170. },
  89171. /**
  89172. * Specifies the vertical size of the blur.
  89173. */
  89174. set: function (value) {
  89175. this._verticalBlurPostprocess.kernel = value;
  89176. },
  89177. enumerable: true,
  89178. configurable: true
  89179. });
  89180. /**
  89181. * Get the effect name of the layer.
  89182. * @return The effect name
  89183. */
  89184. HighlightLayer.prototype.getEffectName = function () {
  89185. return HighlightLayer.EffectName;
  89186. };
  89187. /**
  89188. * Create the merge effect. This is the shader use to blit the information back
  89189. * to the main canvas at the end of the scene rendering.
  89190. */
  89191. HighlightLayer.prototype._createMergeEffect = function () {
  89192. // Effect
  89193. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  89194. };
  89195. /**
  89196. * Creates the render target textures and post processes used in the highlight layer.
  89197. */
  89198. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  89199. var _this = this;
  89200. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  89201. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  89202. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  89203. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  89204. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  89205. width: blurTextureWidth,
  89206. height: blurTextureHeight
  89207. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  89208. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89209. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89210. this._blurTexture.anisotropicFilteringLevel = 16;
  89211. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  89212. this._blurTexture.renderParticles = false;
  89213. this._blurTexture.ignoreCameraViewport = true;
  89214. this._textures = [this._blurTexture];
  89215. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  89216. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  89217. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  89218. effect.setTexture("textureSampler", _this._mainTexture);
  89219. });
  89220. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  89221. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  89222. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  89223. });
  89224. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  89225. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  89226. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  89227. });
  89228. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  89229. }
  89230. else {
  89231. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  89232. width: blurTextureWidth,
  89233. height: blurTextureHeight
  89234. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  89235. this._horizontalBlurPostprocess.width = blurTextureWidth;
  89236. this._horizontalBlurPostprocess.height = blurTextureHeight;
  89237. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  89238. effect.setTexture("textureSampler", _this._mainTexture);
  89239. });
  89240. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  89241. width: blurTextureWidth,
  89242. height: blurTextureHeight
  89243. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  89244. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  89245. }
  89246. this._mainTexture.onAfterUnbindObservable.add(function () {
  89247. _this.onBeforeBlurObservable.notifyObservers(_this);
  89248. var internalTexture = _this._blurTexture.getInternalTexture();
  89249. if (internalTexture) {
  89250. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  89251. }
  89252. _this.onAfterBlurObservable.notifyObservers(_this);
  89253. });
  89254. // Prevent autoClear.
  89255. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  89256. };
  89257. /**
  89258. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  89259. */
  89260. HighlightLayer.prototype.needStencil = function () {
  89261. return true;
  89262. };
  89263. /**
  89264. * Checks for the readiness of the element composing the layer.
  89265. * @param subMesh the mesh to check for
  89266. * @param useInstances specify wether or not to use instances to render the mesh
  89267. * @param emissiveTexture the associated emissive texture used to generate the glow
  89268. * @return true if ready otherwise, false
  89269. */
  89270. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  89271. var material = subMesh.getMaterial();
  89272. var mesh = subMesh.getRenderingMesh();
  89273. if (!material || !mesh || !this._meshes) {
  89274. return false;
  89275. }
  89276. var emissiveTexture = null;
  89277. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  89278. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  89279. emissiveTexture = material.emissiveTexture;
  89280. }
  89281. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  89282. };
  89283. /**
  89284. * Implementation specific of rendering the generating effect on the main canvas.
  89285. * @param effect The effect used to render through
  89286. */
  89287. HighlightLayer.prototype._internalRender = function (effect) {
  89288. // Texture
  89289. effect.setTexture("textureSampler", this._blurTexture);
  89290. // Cache
  89291. var engine = this._engine;
  89292. var previousStencilBuffer = engine.getStencilBuffer();
  89293. var previousStencilFunction = engine.getStencilFunction();
  89294. var previousStencilMask = engine.getStencilMask();
  89295. var previousStencilOperationPass = engine.getStencilOperationPass();
  89296. var previousStencilOperationFail = engine.getStencilOperationFail();
  89297. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  89298. var previousStencilReference = engine.getStencilFunctionReference();
  89299. // Stencil operations
  89300. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  89301. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  89302. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  89303. // Draw order
  89304. engine.setStencilMask(0x00);
  89305. engine.setStencilBuffer(true);
  89306. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  89307. // 2 passes inner outer
  89308. if (this.outerGlow) {
  89309. effect.setFloat("offset", 0);
  89310. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  89311. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  89312. }
  89313. if (this.innerGlow) {
  89314. effect.setFloat("offset", 1);
  89315. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  89316. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  89317. }
  89318. // Restore Cache
  89319. engine.setStencilFunction(previousStencilFunction);
  89320. engine.setStencilMask(previousStencilMask);
  89321. engine.setStencilBuffer(previousStencilBuffer);
  89322. engine.setStencilOperationPass(previousStencilOperationPass);
  89323. engine.setStencilOperationFail(previousStencilOperationFail);
  89324. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  89325. engine.setStencilFunctionReference(previousStencilReference);
  89326. };
  89327. /**
  89328. * Returns true if the layer contains information to display, otherwise false.
  89329. */
  89330. HighlightLayer.prototype.shouldRender = function () {
  89331. if (_super.prototype.shouldRender.call(this)) {
  89332. return this._meshes ? true : false;
  89333. }
  89334. return false;
  89335. };
  89336. /**
  89337. * Returns true if the mesh should render, otherwise false.
  89338. * @param mesh The mesh to render
  89339. * @returns true if it should render otherwise false
  89340. */
  89341. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  89342. // Excluded Mesh
  89343. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  89344. return false;
  89345. }
  89346. ;
  89347. return true;
  89348. };
  89349. /**
  89350. * Sets the required values for both the emissive texture and and the main color.
  89351. */
  89352. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  89353. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  89354. if (highlightLayerMesh) {
  89355. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  89356. }
  89357. else {
  89358. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  89359. }
  89360. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  89361. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  89362. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  89363. }
  89364. else {
  89365. this._emissiveTextureAndColor.texture = null;
  89366. }
  89367. };
  89368. /**
  89369. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  89370. * @param mesh The mesh to exclude from the highlight layer
  89371. */
  89372. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  89373. if (!this._excludedMeshes) {
  89374. return;
  89375. }
  89376. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  89377. if (!meshExcluded) {
  89378. this._excludedMeshes[mesh.uniqueId] = {
  89379. mesh: mesh,
  89380. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  89381. mesh.getEngine().setStencilBuffer(false);
  89382. }),
  89383. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  89384. mesh.getEngine().setStencilBuffer(true);
  89385. }),
  89386. };
  89387. }
  89388. };
  89389. /**
  89390. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  89391. * @param mesh The mesh to highlight
  89392. */
  89393. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  89394. if (!this._excludedMeshes) {
  89395. return;
  89396. }
  89397. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  89398. if (meshExcluded) {
  89399. if (meshExcluded.beforeRender) {
  89400. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  89401. }
  89402. if (meshExcluded.afterRender) {
  89403. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  89404. }
  89405. }
  89406. this._excludedMeshes[mesh.uniqueId] = null;
  89407. };
  89408. /**
  89409. * Determine if a given mesh will be highlighted by the current HighlightLayer
  89410. * @param mesh mesh to test
  89411. * @returns true if the mesh will be highlighted by the current HighlightLayer
  89412. */
  89413. HighlightLayer.prototype.hasMesh = function (mesh) {
  89414. if (!this._meshes) {
  89415. return false;
  89416. }
  89417. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  89418. };
  89419. /**
  89420. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  89421. * @param mesh The mesh to highlight
  89422. * @param color The color of the highlight
  89423. * @param glowEmissiveOnly Extract the glow from the emissive texture
  89424. */
  89425. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  89426. var _this = this;
  89427. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  89428. if (!this._meshes) {
  89429. return;
  89430. }
  89431. var meshHighlight = this._meshes[mesh.uniqueId];
  89432. if (meshHighlight) {
  89433. meshHighlight.color = color;
  89434. }
  89435. else {
  89436. this._meshes[mesh.uniqueId] = {
  89437. mesh: mesh,
  89438. color: color,
  89439. // Lambda required for capture due to Observable this context
  89440. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  89441. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  89442. _this._defaultStencilReference(mesh);
  89443. }
  89444. else {
  89445. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  89446. }
  89447. }),
  89448. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  89449. glowEmissiveOnly: glowEmissiveOnly
  89450. };
  89451. }
  89452. this._shouldRender = true;
  89453. };
  89454. /**
  89455. * Remove a mesh from the highlight layer in order to make it stop glowing.
  89456. * @param mesh The mesh to highlight
  89457. */
  89458. HighlightLayer.prototype.removeMesh = function (mesh) {
  89459. if (!this._meshes) {
  89460. return;
  89461. }
  89462. var meshHighlight = this._meshes[mesh.uniqueId];
  89463. if (meshHighlight) {
  89464. if (meshHighlight.observerHighlight) {
  89465. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  89466. }
  89467. if (meshHighlight.observerDefault) {
  89468. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  89469. }
  89470. delete this._meshes[mesh.uniqueId];
  89471. }
  89472. this._shouldRender = false;
  89473. for (var meshHighlightToCheck in this._meshes) {
  89474. if (this._meshes[meshHighlightToCheck]) {
  89475. this._shouldRender = true;
  89476. break;
  89477. }
  89478. }
  89479. };
  89480. /**
  89481. * Force the stencil to the normal expected value for none glowing parts
  89482. */
  89483. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  89484. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  89485. };
  89486. /**
  89487. * Free any resources and references associated to a mesh.
  89488. * Internal use
  89489. * @param mesh The mesh to free.
  89490. */
  89491. HighlightLayer.prototype._disposeMesh = function (mesh) {
  89492. this.removeMesh(mesh);
  89493. this.removeExcludedMesh(mesh);
  89494. };
  89495. /**
  89496. * Dispose the highlight layer and free resources.
  89497. */
  89498. HighlightLayer.prototype.dispose = function () {
  89499. if (this._meshes) {
  89500. // Clean mesh references
  89501. for (var id in this._meshes) {
  89502. var meshHighlight = this._meshes[id];
  89503. if (meshHighlight && meshHighlight.mesh) {
  89504. if (meshHighlight.observerHighlight) {
  89505. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  89506. }
  89507. if (meshHighlight.observerDefault) {
  89508. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  89509. }
  89510. }
  89511. }
  89512. this._meshes = null;
  89513. }
  89514. if (this._excludedMeshes) {
  89515. for (var id in this._excludedMeshes) {
  89516. var meshHighlight = this._excludedMeshes[id];
  89517. if (meshHighlight) {
  89518. if (meshHighlight.beforeRender) {
  89519. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  89520. }
  89521. if (meshHighlight.afterRender) {
  89522. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  89523. }
  89524. }
  89525. }
  89526. this._excludedMeshes = null;
  89527. }
  89528. _super.prototype.dispose.call(this);
  89529. };
  89530. /**
  89531. * Effect Name of the highlight layer.
  89532. */
  89533. HighlightLayer.EffectName = "HighlightLayer";
  89534. /**
  89535. * The neutral color used during the preparation of the glow effect.
  89536. * This is black by default as the blend operation is a blend operation.
  89537. */
  89538. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  89539. /**
  89540. * Stencil value used for glowing meshes.
  89541. */
  89542. HighlightLayer.GlowingMeshStencilReference = 0x02;
  89543. /**
  89544. * Stencil value used for the other meshes in the scene.
  89545. */
  89546. HighlightLayer.NormalMeshStencilReference = 0x01;
  89547. return HighlightLayer;
  89548. }(BABYLON.EffectLayer));
  89549. BABYLON.HighlightLayer = HighlightLayer;
  89550. })(BABYLON || (BABYLON = {}));
  89551. //# sourceMappingURL=babylon.highlightLayer.js.map
  89552. "use strict";
  89553. var BABYLON;
  89554. (function (BABYLON) {
  89555. /**
  89556. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  89557. *
  89558. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  89559. * glowy meshes to your scene.
  89560. *
  89561. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  89562. */
  89563. var GlowLayer = /** @class */ (function (_super) {
  89564. __extends(GlowLayer, _super);
  89565. /**
  89566. * Instantiates a new glow Layer and references it to the scene.
  89567. * @param name The name of the layer
  89568. * @param scene The scene to use the layer in
  89569. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  89570. */
  89571. function GlowLayer(name, scene, options) {
  89572. var _this = _super.call(this, name, scene) || this;
  89573. _this._intensity = 1.0;
  89574. _this._includedOnlyMeshes = [];
  89575. _this._excludedMeshes = [];
  89576. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  89577. // Adapt options
  89578. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  89579. // Initialize the layer
  89580. _this._init({
  89581. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  89582. camera: _this._options.camera,
  89583. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  89584. mainTextureRatio: _this._options.mainTextureRatio
  89585. });
  89586. return _this;
  89587. }
  89588. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  89589. /**
  89590. * Gets the kernel size of the blur.
  89591. */
  89592. get: function () {
  89593. return this._horizontalBlurPostprocess1.kernel;
  89594. },
  89595. /**
  89596. * Sets the kernel size of the blur.
  89597. */
  89598. set: function (value) {
  89599. this._horizontalBlurPostprocess1.kernel = value;
  89600. this._verticalBlurPostprocess1.kernel = value;
  89601. this._horizontalBlurPostprocess2.kernel = value;
  89602. this._verticalBlurPostprocess2.kernel = value;
  89603. },
  89604. enumerable: true,
  89605. configurable: true
  89606. });
  89607. Object.defineProperty(GlowLayer.prototype, "intensity", {
  89608. /**
  89609. * Gets the glow intensity.
  89610. */
  89611. get: function () {
  89612. return this._intensity;
  89613. },
  89614. /**
  89615. * Sets the glow intensity.
  89616. */
  89617. set: function (value) {
  89618. this._intensity = value;
  89619. },
  89620. enumerable: true,
  89621. configurable: true
  89622. });
  89623. /**
  89624. * Get the effect name of the layer.
  89625. * @return The effect name
  89626. */
  89627. GlowLayer.prototype.getEffectName = function () {
  89628. return GlowLayer.EffectName;
  89629. };
  89630. /**
  89631. * Create the merge effect. This is the shader use to blit the information back
  89632. * to the main canvas at the end of the scene rendering.
  89633. */
  89634. GlowLayer.prototype._createMergeEffect = function () {
  89635. // Effect
  89636. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  89637. };
  89638. /**
  89639. * Creates the render target textures and post processes used in the glow layer.
  89640. */
  89641. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  89642. var _this = this;
  89643. var blurTextureWidth = this._mainTextureDesiredSize.width;
  89644. var blurTextureHeight = this._mainTextureDesiredSize.height;
  89645. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  89646. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  89647. var textureType = 0;
  89648. if (this._engine.getCaps().textureHalfFloatRender) {
  89649. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  89650. }
  89651. else {
  89652. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  89653. }
  89654. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  89655. width: blurTextureWidth,
  89656. height: blurTextureHeight
  89657. }, this._scene, false, true, textureType);
  89658. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89659. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89660. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  89661. this._blurTexture1.renderParticles = false;
  89662. this._blurTexture1.ignoreCameraViewport = true;
  89663. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  89664. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  89665. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  89666. width: blurTextureWidth2,
  89667. height: blurTextureHeight2
  89668. }, this._scene, false, true, textureType);
  89669. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89670. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89671. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  89672. this._blurTexture2.renderParticles = false;
  89673. this._blurTexture2.ignoreCameraViewport = true;
  89674. this._textures = [this._blurTexture1, this._blurTexture2];
  89675. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  89676. width: blurTextureWidth,
  89677. height: blurTextureHeight
  89678. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  89679. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  89680. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  89681. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  89682. effect.setTexture("textureSampler", _this._mainTexture);
  89683. });
  89684. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  89685. width: blurTextureWidth,
  89686. height: blurTextureHeight
  89687. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  89688. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  89689. width: blurTextureWidth2,
  89690. height: blurTextureHeight2
  89691. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  89692. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  89693. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  89694. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  89695. effect.setTexture("textureSampler", _this._blurTexture1);
  89696. });
  89697. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  89698. width: blurTextureWidth2,
  89699. height: blurTextureHeight2
  89700. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  89701. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  89702. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  89703. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  89704. this._mainTexture.samples = this._options.mainTextureSamples;
  89705. this._mainTexture.onAfterUnbindObservable.add(function () {
  89706. var internalTexture = _this._blurTexture1.getInternalTexture();
  89707. if (internalTexture) {
  89708. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  89709. internalTexture = _this._blurTexture2.getInternalTexture();
  89710. if (internalTexture) {
  89711. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  89712. }
  89713. }
  89714. });
  89715. // Prevent autoClear.
  89716. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  89717. };
  89718. /**
  89719. * Checks for the readiness of the element composing the layer.
  89720. * @param subMesh the mesh to check for
  89721. * @param useInstances specify wether or not to use instances to render the mesh
  89722. * @param emissiveTexture the associated emissive texture used to generate the glow
  89723. * @return true if ready otherwise, false
  89724. */
  89725. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  89726. var material = subMesh.getMaterial();
  89727. var mesh = subMesh.getRenderingMesh();
  89728. if (!material || !mesh) {
  89729. return false;
  89730. }
  89731. var emissiveTexture = material.emissiveTexture;
  89732. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  89733. };
  89734. /**
  89735. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  89736. */
  89737. GlowLayer.prototype.needStencil = function () {
  89738. return false;
  89739. };
  89740. /**
  89741. * Implementation specific of rendering the generating effect on the main canvas.
  89742. * @param effect The effect used to render through
  89743. */
  89744. GlowLayer.prototype._internalRender = function (effect) {
  89745. // Texture
  89746. effect.setTexture("textureSampler", this._blurTexture1);
  89747. effect.setTexture("textureSampler2", this._blurTexture2);
  89748. effect.setFloat("offset", this._intensity);
  89749. // Cache
  89750. var engine = this._engine;
  89751. var previousStencilBuffer = engine.getStencilBuffer();
  89752. // Draw order
  89753. engine.setStencilBuffer(false);
  89754. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  89755. // Draw order
  89756. engine.setStencilBuffer(previousStencilBuffer);
  89757. };
  89758. /**
  89759. * Sets the required values for both the emissive texture and and the main color.
  89760. */
  89761. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  89762. var textureLevel = 1.0;
  89763. if (this.customEmissiveTextureSelector) {
  89764. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  89765. }
  89766. else {
  89767. if (material) {
  89768. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  89769. if (this._emissiveTextureAndColor.texture) {
  89770. textureLevel = this._emissiveTextureAndColor.texture.level;
  89771. }
  89772. }
  89773. else {
  89774. this._emissiveTextureAndColor.texture = null;
  89775. }
  89776. }
  89777. if (this.customEmissiveColorSelector) {
  89778. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  89779. }
  89780. else {
  89781. if (material.emissiveColor) {
  89782. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  89783. }
  89784. else {
  89785. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  89786. }
  89787. }
  89788. };
  89789. /**
  89790. * Returns true if the mesh should render, otherwise false.
  89791. * @param mesh The mesh to render
  89792. * @returns true if it should render otherwise false
  89793. */
  89794. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  89795. return this.hasMesh(mesh);
  89796. };
  89797. /**
  89798. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  89799. * @param mesh The mesh to exclude from the glow layer
  89800. */
  89801. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  89802. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  89803. this._excludedMeshes.push(mesh.uniqueId);
  89804. }
  89805. };
  89806. /**
  89807. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  89808. * @param mesh The mesh to remove
  89809. */
  89810. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  89811. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  89812. if (index !== -1) {
  89813. this._excludedMeshes.splice(index, 1);
  89814. }
  89815. };
  89816. /**
  89817. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  89818. * @param mesh The mesh to include in the glow layer
  89819. */
  89820. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  89821. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  89822. this._includedOnlyMeshes.push(mesh.uniqueId);
  89823. }
  89824. };
  89825. /**
  89826. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  89827. * @param mesh The mesh to remove
  89828. */
  89829. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  89830. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  89831. if (index !== -1) {
  89832. this._includedOnlyMeshes.splice(index, 1);
  89833. }
  89834. };
  89835. /**
  89836. * Determine if a given mesh will be used in the glow layer
  89837. * @param mesh The mesh to test
  89838. * @returns true if the mesh will be highlighted by the current glow layer
  89839. */
  89840. GlowLayer.prototype.hasMesh = function (mesh) {
  89841. // Included Mesh
  89842. if (this._includedOnlyMeshes.length) {
  89843. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  89844. }
  89845. ;
  89846. // Excluded Mesh
  89847. if (this._excludedMeshes.length) {
  89848. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  89849. }
  89850. ;
  89851. return true;
  89852. };
  89853. /**
  89854. * Free any resources and references associated to a mesh.
  89855. * Internal use
  89856. * @param mesh The mesh to free.
  89857. */
  89858. GlowLayer.prototype._disposeMesh = function (mesh) {
  89859. this.removeIncludedOnlyMesh(mesh);
  89860. this.removeExcludedMesh(mesh);
  89861. };
  89862. /**
  89863. * Gets the class name of the effect layer
  89864. * @returns the string with the class name of the effect layer
  89865. */
  89866. GlowLayer.prototype.getClassName = function () {
  89867. return "GlowLayer";
  89868. };
  89869. /**
  89870. * Serializes this glow layer
  89871. * @returns a serialized glow layer object
  89872. */
  89873. GlowLayer.prototype.serialize = function () {
  89874. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  89875. var index;
  89876. // Included meshes
  89877. serializationObject.includedMeshes = [];
  89878. if (this._includedOnlyMeshes.length) {
  89879. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  89880. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  89881. if (mesh) {
  89882. serializationObject.includedMeshes.push(mesh.id);
  89883. }
  89884. }
  89885. }
  89886. // Excluded meshes
  89887. serializationObject.excludedMeshes = [];
  89888. if (this._excludedMeshes.length) {
  89889. for (index = 0; index < this._excludedMeshes.length; index++) {
  89890. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  89891. if (mesh) {
  89892. serializationObject.excludedMeshes.push(mesh.id);
  89893. }
  89894. }
  89895. }
  89896. return serializationObject;
  89897. };
  89898. /**
  89899. * Creates a Glow Layer from parsed glow layer data
  89900. * @param parsedGlowLayer defines glow layer data
  89901. * @param scene defines the current scene
  89902. * @param rootUrl defines the root URL containing the glow layer information
  89903. * @returns a parsed Glow Layer
  89904. */
  89905. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  89906. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  89907. var index;
  89908. // Excluded meshes
  89909. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  89910. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  89911. if (mesh) {
  89912. gl.addExcludedMesh(mesh);
  89913. }
  89914. }
  89915. // Included meshes
  89916. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  89917. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  89918. if (mesh) {
  89919. gl.addIncludedOnlyMesh(mesh);
  89920. }
  89921. }
  89922. return gl;
  89923. };
  89924. /**
  89925. * Effect Name of the layer.
  89926. */
  89927. GlowLayer.EffectName = "GlowLayer";
  89928. /**
  89929. * The default blur kernel size used for the glow.
  89930. */
  89931. GlowLayer.DefaultBlurKernelSize = 32;
  89932. /**
  89933. * The default texture size ratio used for the glow.
  89934. */
  89935. GlowLayer.DefaultTextureRatio = 0.5;
  89936. __decorate([
  89937. BABYLON.serialize()
  89938. ], GlowLayer.prototype, "blurKernelSize", null);
  89939. __decorate([
  89940. BABYLON.serialize()
  89941. ], GlowLayer.prototype, "intensity", null);
  89942. __decorate([
  89943. BABYLON.serialize('options')
  89944. ], GlowLayer.prototype, "_options", void 0);
  89945. return GlowLayer;
  89946. }(BABYLON.EffectLayer));
  89947. BABYLON.GlowLayer = GlowLayer;
  89948. })(BABYLON || (BABYLON = {}));
  89949. //# sourceMappingURL=babylon.glowLayer.js.map
  89950. "use strict";
  89951. var BABYLON;
  89952. (function (BABYLON) {
  89953. /**
  89954. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  89955. */
  89956. var AssetTaskState;
  89957. (function (AssetTaskState) {
  89958. /**
  89959. * Initialization
  89960. */
  89961. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  89962. /**
  89963. * Running
  89964. */
  89965. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  89966. /**
  89967. * Done
  89968. */
  89969. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  89970. /**
  89971. * Error
  89972. */
  89973. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  89974. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  89975. /**
  89976. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  89977. */
  89978. var AbstractAssetTask = /** @class */ (function () {
  89979. /**
  89980. * Creates a new {BABYLON.AssetsManager}
  89981. * @param name defines the name of the task
  89982. */
  89983. function AbstractAssetTask(
  89984. /**
  89985. * Task name
  89986. */ name) {
  89987. this.name = name;
  89988. this._isCompleted = false;
  89989. this._taskState = AssetTaskState.INIT;
  89990. }
  89991. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  89992. /**
  89993. * Get if the task is completed
  89994. */
  89995. get: function () {
  89996. return this._isCompleted;
  89997. },
  89998. enumerable: true,
  89999. configurable: true
  90000. });
  90001. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  90002. /**
  90003. * Gets the current state of the task
  90004. */
  90005. get: function () {
  90006. return this._taskState;
  90007. },
  90008. enumerable: true,
  90009. configurable: true
  90010. });
  90011. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  90012. /**
  90013. * Gets the current error object (if task is in error)
  90014. */
  90015. get: function () {
  90016. return this._errorObject;
  90017. },
  90018. enumerable: true,
  90019. configurable: true
  90020. });
  90021. /**
  90022. * Internal only
  90023. * @ignore
  90024. */
  90025. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  90026. if (this._errorObject) {
  90027. return;
  90028. }
  90029. this._errorObject = {
  90030. message: message,
  90031. exception: exception
  90032. };
  90033. };
  90034. /**
  90035. * Execute the current task
  90036. * @param scene defines the scene where you want your assets to be loaded
  90037. * @param onSuccess is a callback called when the task is successfully executed
  90038. * @param onError is a callback called if an error occurs
  90039. */
  90040. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  90041. var _this = this;
  90042. this._taskState = AssetTaskState.RUNNING;
  90043. this.runTask(scene, function () {
  90044. _this.onDoneCallback(onSuccess, onError);
  90045. }, function (msg, exception) {
  90046. _this.onErrorCallback(onError, msg, exception);
  90047. });
  90048. };
  90049. /**
  90050. * Execute the current task
  90051. * @param scene defines the scene where you want your assets to be loaded
  90052. * @param onSuccess is a callback called when the task is successfully executed
  90053. * @param onError is a callback called if an error occurs
  90054. */
  90055. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  90056. throw new Error("runTask is not implemented");
  90057. };
  90058. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  90059. this._taskState = AssetTaskState.ERROR;
  90060. this._errorObject = {
  90061. message: message,
  90062. exception: exception
  90063. };
  90064. if (this.onError) {
  90065. this.onError(this, message, exception);
  90066. }
  90067. onError();
  90068. };
  90069. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  90070. try {
  90071. this._taskState = AssetTaskState.DONE;
  90072. this._isCompleted = true;
  90073. if (this.onSuccess) {
  90074. this.onSuccess(this);
  90075. }
  90076. onSuccess();
  90077. }
  90078. catch (e) {
  90079. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  90080. }
  90081. };
  90082. return AbstractAssetTask;
  90083. }());
  90084. BABYLON.AbstractAssetTask = AbstractAssetTask;
  90085. /**
  90086. * Class used to share progress information about assets loading
  90087. */
  90088. var AssetsProgressEvent = /** @class */ (function () {
  90089. /**
  90090. * Creates a {BABYLON.AssetsProgressEvent}
  90091. * @param remainingCount defines the number of remaining tasks to process
  90092. * @param totalCount defines the total number of tasks
  90093. * @param task defines the task that was just processed
  90094. */
  90095. function AssetsProgressEvent(remainingCount, totalCount, task) {
  90096. this.remainingCount = remainingCount;
  90097. this.totalCount = totalCount;
  90098. this.task = task;
  90099. }
  90100. return AssetsProgressEvent;
  90101. }());
  90102. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  90103. /**
  90104. * Define a task used by {BABYLON.AssetsManager} to load meshes
  90105. */
  90106. var MeshAssetTask = /** @class */ (function (_super) {
  90107. __extends(MeshAssetTask, _super);
  90108. /**
  90109. * Creates a new {BABYLON.MeshAssetTask}
  90110. * @param name defines the name of the task
  90111. * @param meshesNames defines the list of mesh's names you want to load
  90112. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  90113. * @param sceneFilename defines the filename of the scene to load from
  90114. */
  90115. function MeshAssetTask(
  90116. /**
  90117. * Defines the name of the task
  90118. */
  90119. name,
  90120. /**
  90121. * Defines the list of mesh's names you want to load
  90122. */
  90123. meshesNames,
  90124. /**
  90125. * Defines the root url to use as a base to load your meshes and associated resources
  90126. */
  90127. rootUrl,
  90128. /**
  90129. * Defines the filename of the scene to load from
  90130. */
  90131. sceneFilename) {
  90132. var _this = _super.call(this, name) || this;
  90133. _this.name = name;
  90134. _this.meshesNames = meshesNames;
  90135. _this.rootUrl = rootUrl;
  90136. _this.sceneFilename = sceneFilename;
  90137. return _this;
  90138. }
  90139. /**
  90140. * Execute the current task
  90141. * @param scene defines the scene where you want your assets to be loaded
  90142. * @param onSuccess is a callback called when the task is successfully executed
  90143. * @param onError is a callback called if an error occurs
  90144. */
  90145. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  90146. var _this = this;
  90147. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  90148. _this.loadedMeshes = meshes;
  90149. _this.loadedParticleSystems = particleSystems;
  90150. _this.loadedSkeletons = skeletons;
  90151. onSuccess();
  90152. }, null, function (scene, message, exception) {
  90153. onError(message, exception);
  90154. });
  90155. };
  90156. return MeshAssetTask;
  90157. }(AbstractAssetTask));
  90158. BABYLON.MeshAssetTask = MeshAssetTask;
  90159. /**
  90160. * Define a task used by {BABYLON.AssetsManager} to load text content
  90161. */
  90162. var TextFileAssetTask = /** @class */ (function (_super) {
  90163. __extends(TextFileAssetTask, _super);
  90164. /**
  90165. * Creates a new TextFileAssetTask object
  90166. * @param name defines the name of the task
  90167. * @param url defines the location of the file to load
  90168. */
  90169. function TextFileAssetTask(
  90170. /**
  90171. * Defines the name of the task
  90172. */
  90173. name,
  90174. /**
  90175. * Defines the location of the file to load
  90176. */
  90177. url) {
  90178. var _this = _super.call(this, name) || this;
  90179. _this.name = name;
  90180. _this.url = url;
  90181. return _this;
  90182. }
  90183. /**
  90184. * Execute the current task
  90185. * @param scene defines the scene where you want your assets to be loaded
  90186. * @param onSuccess is a callback called when the task is successfully executed
  90187. * @param onError is a callback called if an error occurs
  90188. */
  90189. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  90190. var _this = this;
  90191. scene._loadFile(this.url, function (data) {
  90192. _this.text = data;
  90193. onSuccess();
  90194. }, undefined, false, false, function (request, exception) {
  90195. if (request) {
  90196. onError(request.status + " " + request.statusText, exception);
  90197. }
  90198. });
  90199. };
  90200. return TextFileAssetTask;
  90201. }(AbstractAssetTask));
  90202. BABYLON.TextFileAssetTask = TextFileAssetTask;
  90203. /**
  90204. * Define a task used by {BABYLON.AssetsManager} to load binary data
  90205. */
  90206. var BinaryFileAssetTask = /** @class */ (function (_super) {
  90207. __extends(BinaryFileAssetTask, _super);
  90208. /**
  90209. * Creates a new BinaryFileAssetTask object
  90210. * @param name defines the name of the new task
  90211. * @param url defines the location of the file to load
  90212. */
  90213. function BinaryFileAssetTask(
  90214. /**
  90215. * Defines the name of the task
  90216. */
  90217. name,
  90218. /**
  90219. * Defines the location of the file to load
  90220. */
  90221. url) {
  90222. var _this = _super.call(this, name) || this;
  90223. _this.name = name;
  90224. _this.url = url;
  90225. return _this;
  90226. }
  90227. /**
  90228. * Execute the current task
  90229. * @param scene defines the scene where you want your assets to be loaded
  90230. * @param onSuccess is a callback called when the task is successfully executed
  90231. * @param onError is a callback called if an error occurs
  90232. */
  90233. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  90234. var _this = this;
  90235. scene._loadFile(this.url, function (data) {
  90236. _this.data = data;
  90237. onSuccess();
  90238. }, undefined, true, true, function (request, exception) {
  90239. if (request) {
  90240. onError(request.status + " " + request.statusText, exception);
  90241. }
  90242. });
  90243. };
  90244. return BinaryFileAssetTask;
  90245. }(AbstractAssetTask));
  90246. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  90247. /**
  90248. * Define a task used by {BABYLON.AssetsManager} to load images
  90249. */
  90250. var ImageAssetTask = /** @class */ (function (_super) {
  90251. __extends(ImageAssetTask, _super);
  90252. /**
  90253. * Creates a new ImageAssetTask
  90254. * @param name defines the name of the task
  90255. * @param url defines the location of the image to load
  90256. */
  90257. function ImageAssetTask(
  90258. /**
  90259. * Defines the name of the task
  90260. */
  90261. name,
  90262. /**
  90263. * Defines the location of the image to load
  90264. */
  90265. url) {
  90266. var _this = _super.call(this, name) || this;
  90267. _this.name = name;
  90268. _this.url = url;
  90269. return _this;
  90270. }
  90271. /**
  90272. * Execute the current task
  90273. * @param scene defines the scene where you want your assets to be loaded
  90274. * @param onSuccess is a callback called when the task is successfully executed
  90275. * @param onError is a callback called if an error occurs
  90276. */
  90277. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  90278. var _this = this;
  90279. var img = new Image();
  90280. BABYLON.Tools.SetCorsBehavior(this.url, img);
  90281. img.onload = function () {
  90282. _this.image = img;
  90283. onSuccess();
  90284. };
  90285. img.onerror = function (err) {
  90286. onError("Error loading image", err);
  90287. };
  90288. img.src = this.url;
  90289. };
  90290. return ImageAssetTask;
  90291. }(AbstractAssetTask));
  90292. BABYLON.ImageAssetTask = ImageAssetTask;
  90293. /**
  90294. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  90295. */
  90296. var TextureAssetTask = /** @class */ (function (_super) {
  90297. __extends(TextureAssetTask, _super);
  90298. /**
  90299. * Creates a new TextureAssetTask object
  90300. * @param name defines the name of the task
  90301. * @param url defines the location of the file to load
  90302. * @param noMipmap defines if mipmap should not be generated (default is false)
  90303. * @param invertY defines if texture must be inverted on Y axis (default is false)
  90304. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  90305. */
  90306. function TextureAssetTask(
  90307. /**
  90308. * Defines the name of the task
  90309. */
  90310. name,
  90311. /**
  90312. * Defines the location of the file to load
  90313. */
  90314. url,
  90315. /**
  90316. * Defines if mipmap should not be generated (default is false)
  90317. */
  90318. noMipmap,
  90319. /**
  90320. * Defines if texture must be inverted on Y axis (default is false)
  90321. */
  90322. invertY,
  90323. /**
  90324. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  90325. */
  90326. samplingMode) {
  90327. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  90328. var _this = _super.call(this, name) || this;
  90329. _this.name = name;
  90330. _this.url = url;
  90331. _this.noMipmap = noMipmap;
  90332. _this.invertY = invertY;
  90333. _this.samplingMode = samplingMode;
  90334. return _this;
  90335. }
  90336. /**
  90337. * Execute the current task
  90338. * @param scene defines the scene where you want your assets to be loaded
  90339. * @param onSuccess is a callback called when the task is successfully executed
  90340. * @param onError is a callback called if an error occurs
  90341. */
  90342. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  90343. var onload = function () {
  90344. onSuccess();
  90345. };
  90346. var onerror = function (message, exception) {
  90347. onError(message, exception);
  90348. };
  90349. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  90350. };
  90351. return TextureAssetTask;
  90352. }(AbstractAssetTask));
  90353. BABYLON.TextureAssetTask = TextureAssetTask;
  90354. /**
  90355. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  90356. */
  90357. var CubeTextureAssetTask = /** @class */ (function (_super) {
  90358. __extends(CubeTextureAssetTask, _super);
  90359. /**
  90360. * Creates a new CubeTextureAssetTask
  90361. * @param name defines the name of the task
  90362. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  90363. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  90364. * @param noMipmap defines if mipmaps should not be generated (default is false)
  90365. * @param files defines the explicit list of files (undefined by default)
  90366. */
  90367. function CubeTextureAssetTask(
  90368. /**
  90369. * Defines the name of the task
  90370. */
  90371. name,
  90372. /**
  90373. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  90374. */
  90375. url,
  90376. /**
  90377. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  90378. */
  90379. extensions,
  90380. /**
  90381. * Defines if mipmaps should not be generated (default is false)
  90382. */
  90383. noMipmap,
  90384. /**
  90385. * Defines the explicit list of files (undefined by default)
  90386. */
  90387. files) {
  90388. var _this = _super.call(this, name) || this;
  90389. _this.name = name;
  90390. _this.url = url;
  90391. _this.extensions = extensions;
  90392. _this.noMipmap = noMipmap;
  90393. _this.files = files;
  90394. return _this;
  90395. }
  90396. /**
  90397. * Execute the current task
  90398. * @param scene defines the scene where you want your assets to be loaded
  90399. * @param onSuccess is a callback called when the task is successfully executed
  90400. * @param onError is a callback called if an error occurs
  90401. */
  90402. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  90403. var onload = function () {
  90404. onSuccess();
  90405. };
  90406. var onerror = function (message, exception) {
  90407. onError(message, exception);
  90408. };
  90409. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  90410. };
  90411. return CubeTextureAssetTask;
  90412. }(AbstractAssetTask));
  90413. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  90414. /**
  90415. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  90416. */
  90417. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  90418. __extends(HDRCubeTextureAssetTask, _super);
  90419. /**
  90420. * Creates a new HDRCubeTextureAssetTask object
  90421. * @param name defines the name of the task
  90422. * @param url defines the location of the file to load
  90423. * @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.
  90424. * @param noMipmap defines if mipmaps should not be generated (default is false)
  90425. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  90426. * @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)
  90427. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  90428. */
  90429. function HDRCubeTextureAssetTask(
  90430. /**
  90431. * Defines the name of the task
  90432. */
  90433. name,
  90434. /**
  90435. * Defines the location of the file to load
  90436. */
  90437. url,
  90438. /**
  90439. * 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.
  90440. */
  90441. size,
  90442. /**
  90443. * Defines if mipmaps should not be generated (default is false)
  90444. */
  90445. noMipmap,
  90446. /**
  90447. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  90448. */
  90449. generateHarmonics,
  90450. /**
  90451. * 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)
  90452. */
  90453. useInGammaSpace,
  90454. /**
  90455. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  90456. */
  90457. usePMREMGenerator) {
  90458. if (noMipmap === void 0) { noMipmap = false; }
  90459. if (generateHarmonics === void 0) { generateHarmonics = true; }
  90460. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  90461. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  90462. var _this = _super.call(this, name) || this;
  90463. _this.name = name;
  90464. _this.url = url;
  90465. _this.size = size;
  90466. _this.noMipmap = noMipmap;
  90467. _this.generateHarmonics = generateHarmonics;
  90468. _this.useInGammaSpace = useInGammaSpace;
  90469. _this.usePMREMGenerator = usePMREMGenerator;
  90470. return _this;
  90471. }
  90472. /**
  90473. * Execute the current task
  90474. * @param scene defines the scene where you want your assets to be loaded
  90475. * @param onSuccess is a callback called when the task is successfully executed
  90476. * @param onError is a callback called if an error occurs
  90477. */
  90478. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  90479. var onload = function () {
  90480. onSuccess();
  90481. };
  90482. var onerror = function (message, exception) {
  90483. onError(message, exception);
  90484. };
  90485. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  90486. };
  90487. return HDRCubeTextureAssetTask;
  90488. }(AbstractAssetTask));
  90489. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  90490. /**
  90491. * This class can be used to easily import assets into a scene
  90492. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  90493. */
  90494. var AssetsManager = /** @class */ (function () {
  90495. /**
  90496. * Creates a new AssetsManager
  90497. * @param scene defines the scene to work on
  90498. */
  90499. function AssetsManager(scene) {
  90500. this._isLoading = false;
  90501. this._tasks = new Array();
  90502. this._waitingTasksCount = 0;
  90503. this._totalTasksCount = 0;
  90504. /**
  90505. * Observable called when all tasks are processed
  90506. */
  90507. this.onTaskSuccessObservable = new BABYLON.Observable();
  90508. /**
  90509. * Observable called when a task had an error
  90510. */
  90511. this.onTaskErrorObservable = new BABYLON.Observable();
  90512. /**
  90513. * Observable called when a task is successful
  90514. */
  90515. this.onTasksDoneObservable = new BABYLON.Observable();
  90516. /**
  90517. * Observable called when a task is done (whatever the result is)
  90518. */
  90519. this.onProgressObservable = new BABYLON.Observable();
  90520. /**
  90521. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  90522. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  90523. */
  90524. this.useDefaultLoadingScreen = true;
  90525. this._scene = scene;
  90526. }
  90527. /**
  90528. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  90529. * @param taskName defines the name of the new task
  90530. * @param meshesNames defines the name of meshes to load
  90531. * @param rootUrl defines the root url to use to locate files
  90532. * @param sceneFilename defines the filename of the scene file
  90533. * @returns a new {BABYLON.MeshAssetTask} object
  90534. */
  90535. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  90536. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  90537. this._tasks.push(task);
  90538. return task;
  90539. };
  90540. /**
  90541. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  90542. * @param taskName defines the name of the new task
  90543. * @param url defines the url of the file to load
  90544. * @returns a new {BABYLON.TextFileAssetTask} object
  90545. */
  90546. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  90547. var task = new TextFileAssetTask(taskName, url);
  90548. this._tasks.push(task);
  90549. return task;
  90550. };
  90551. /**
  90552. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  90553. * @param taskName defines the name of the new task
  90554. * @param url defines the url of the file to load
  90555. * @returns a new {BABYLON.BinaryFileAssetTask} object
  90556. */
  90557. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  90558. var task = new BinaryFileAssetTask(taskName, url);
  90559. this._tasks.push(task);
  90560. return task;
  90561. };
  90562. /**
  90563. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  90564. * @param taskName defines the name of the new task
  90565. * @param url defines the url of the file to load
  90566. * @returns a new {BABYLON.ImageAssetTask} object
  90567. */
  90568. AssetsManager.prototype.addImageTask = function (taskName, url) {
  90569. var task = new ImageAssetTask(taskName, url);
  90570. this._tasks.push(task);
  90571. return task;
  90572. };
  90573. /**
  90574. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  90575. * @param taskName defines the name of the new task
  90576. * @param url defines the url of the file to load
  90577. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  90578. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  90579. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  90580. * @returns a new {BABYLON.TextureAssetTask} object
  90581. */
  90582. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  90583. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  90584. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  90585. this._tasks.push(task);
  90586. return task;
  90587. };
  90588. /**
  90589. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  90590. * @param taskName defines the name of the new task
  90591. * @param url defines the url of the file to load
  90592. * @param extensions defines the extension to use to load the cube map (can be null)
  90593. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  90594. * @param files defines the list of files to load (can be null)
  90595. * @returns a new {BABYLON.CubeTextureAssetTask} object
  90596. */
  90597. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  90598. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  90599. this._tasks.push(task);
  90600. return task;
  90601. };
  90602. /**
  90603. *
  90604. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  90605. * @param taskName defines the name of the new task
  90606. * @param url defines the url of the file to load
  90607. * @param size defines the size you want for the cubemap (can be null)
  90608. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  90609. * @param generateHarmonics defines if you want to automatically generate (true by default)
  90610. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  90611. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  90612. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  90613. */
  90614. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  90615. if (noMipmap === void 0) { noMipmap = false; }
  90616. if (generateHarmonics === void 0) { generateHarmonics = true; }
  90617. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  90618. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  90619. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  90620. this._tasks.push(task);
  90621. return task;
  90622. };
  90623. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  90624. var _this = this;
  90625. this._waitingTasksCount--;
  90626. try {
  90627. if (task.taskState === AssetTaskState.DONE) {
  90628. // Let's remove successfull tasks
  90629. BABYLON.Tools.SetImmediate(function () {
  90630. var index = _this._tasks.indexOf(task);
  90631. if (index > -1) {
  90632. _this._tasks.splice(index, 1);
  90633. }
  90634. });
  90635. }
  90636. if (this.onProgress) {
  90637. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  90638. }
  90639. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  90640. }
  90641. catch (e) {
  90642. BABYLON.Tools.Error("Error running progress callbacks.");
  90643. console.log(e);
  90644. }
  90645. if (this._waitingTasksCount === 0) {
  90646. try {
  90647. if (this.onFinish) {
  90648. this.onFinish(this._tasks);
  90649. }
  90650. this.onTasksDoneObservable.notifyObservers(this._tasks);
  90651. }
  90652. catch (e) {
  90653. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  90654. console.log(e);
  90655. }
  90656. this._isLoading = false;
  90657. this._scene.getEngine().hideLoadingUI();
  90658. }
  90659. };
  90660. AssetsManager.prototype._runTask = function (task) {
  90661. var _this = this;
  90662. var done = function () {
  90663. try {
  90664. if (_this.onTaskSuccess) {
  90665. _this.onTaskSuccess(task);
  90666. }
  90667. _this.onTaskSuccessObservable.notifyObservers(task);
  90668. _this._decreaseWaitingTasksCount(task);
  90669. }
  90670. catch (e) {
  90671. error("Error executing task success callbacks", e);
  90672. }
  90673. };
  90674. var error = function (message, exception) {
  90675. task._setErrorObject(message, exception);
  90676. if (_this.onTaskError) {
  90677. _this.onTaskError(task);
  90678. }
  90679. _this.onTaskErrorObservable.notifyObservers(task);
  90680. _this._decreaseWaitingTasksCount(task);
  90681. };
  90682. task.run(this._scene, done, error);
  90683. };
  90684. /**
  90685. * Reset the {BABYLON.AssetsManager} and remove all tasks
  90686. * @return the current instance of the {BABYLON.AssetsManager}
  90687. */
  90688. AssetsManager.prototype.reset = function () {
  90689. this._isLoading = false;
  90690. this._tasks = new Array();
  90691. return this;
  90692. };
  90693. /**
  90694. * Start the loading process
  90695. * @return the current instance of the {BABYLON.AssetsManager}
  90696. */
  90697. AssetsManager.prototype.load = function () {
  90698. if (this._isLoading) {
  90699. return this;
  90700. }
  90701. this._isLoading = true;
  90702. this._waitingTasksCount = this._tasks.length;
  90703. this._totalTasksCount = this._tasks.length;
  90704. if (this._waitingTasksCount === 0) {
  90705. this._isLoading = false;
  90706. if (this.onFinish) {
  90707. this.onFinish(this._tasks);
  90708. }
  90709. this.onTasksDoneObservable.notifyObservers(this._tasks);
  90710. return this;
  90711. }
  90712. if (this.useDefaultLoadingScreen) {
  90713. this._scene.getEngine().displayLoadingUI();
  90714. }
  90715. for (var index = 0; index < this._tasks.length; index++) {
  90716. var task = this._tasks[index];
  90717. this._runTask(task);
  90718. }
  90719. return this;
  90720. };
  90721. return AssetsManager;
  90722. }());
  90723. BABYLON.AssetsManager = AssetsManager;
  90724. })(BABYLON || (BABYLON = {}));
  90725. //# sourceMappingURL=babylon.assetsManager.js.map
  90726. "use strict";
  90727. var BABYLON;
  90728. (function (BABYLON) {
  90729. var serializedGeometries = [];
  90730. var serializeGeometry = function (geometry, serializationGeometries) {
  90731. if (serializedGeometries[geometry.id]) {
  90732. return;
  90733. }
  90734. if (geometry.doNotSerialize) {
  90735. return;
  90736. }
  90737. if (geometry instanceof BABYLON.BoxGeometry) {
  90738. serializationGeometries.boxes.push(geometry.serialize());
  90739. }
  90740. else if (geometry instanceof BABYLON.SphereGeometry) {
  90741. serializationGeometries.spheres.push(geometry.serialize());
  90742. }
  90743. else if (geometry instanceof BABYLON.CylinderGeometry) {
  90744. serializationGeometries.cylinders.push(geometry.serialize());
  90745. }
  90746. else if (geometry instanceof BABYLON.TorusGeometry) {
  90747. serializationGeometries.toruses.push(geometry.serialize());
  90748. }
  90749. else if (geometry instanceof BABYLON.GroundGeometry) {
  90750. serializationGeometries.grounds.push(geometry.serialize());
  90751. }
  90752. else if (geometry instanceof BABYLON.Plane) {
  90753. serializationGeometries.planes.push(geometry.serialize());
  90754. }
  90755. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  90756. serializationGeometries.torusKnots.push(geometry.serialize());
  90757. }
  90758. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  90759. throw new Error("Unknown primitive type");
  90760. }
  90761. else {
  90762. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  90763. }
  90764. serializedGeometries[geometry.id] = true;
  90765. };
  90766. var serializeMesh = function (mesh, serializationScene) {
  90767. var serializationObject = {};
  90768. // Geometry
  90769. var geometry = mesh._geometry;
  90770. if (geometry) {
  90771. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  90772. // 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
  90773. serializeGeometry(geometry, serializationScene.geometries);
  90774. }
  90775. }
  90776. // Custom
  90777. if (mesh.serialize) {
  90778. mesh.serialize(serializationObject);
  90779. }
  90780. return serializationObject;
  90781. };
  90782. var finalizeSingleMesh = function (mesh, serializationObject) {
  90783. //only works if the mesh is already loaded
  90784. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  90785. //serialize material
  90786. if (mesh.material) {
  90787. if (mesh.material instanceof BABYLON.StandardMaterial) {
  90788. serializationObject.materials = serializationObject.materials || [];
  90789. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  90790. serializationObject.materials.push(mesh.material.serialize());
  90791. }
  90792. }
  90793. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  90794. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  90795. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  90796. serializationObject.multiMaterials.push(mesh.material.serialize());
  90797. }
  90798. }
  90799. }
  90800. //serialize geometry
  90801. var geometry = mesh._geometry;
  90802. if (geometry) {
  90803. if (!serializationObject.geometries) {
  90804. serializationObject.geometries = {};
  90805. serializationObject.geometries.boxes = [];
  90806. serializationObject.geometries.spheres = [];
  90807. serializationObject.geometries.cylinders = [];
  90808. serializationObject.geometries.toruses = [];
  90809. serializationObject.geometries.grounds = [];
  90810. serializationObject.geometries.planes = [];
  90811. serializationObject.geometries.torusKnots = [];
  90812. serializationObject.geometries.vertexData = [];
  90813. }
  90814. serializeGeometry(geometry, serializationObject.geometries);
  90815. }
  90816. // Skeletons
  90817. if (mesh.skeleton) {
  90818. serializationObject.skeletons = serializationObject.skeletons || [];
  90819. serializationObject.skeletons.push(mesh.skeleton.serialize());
  90820. }
  90821. //serialize the actual mesh
  90822. serializationObject.meshes = serializationObject.meshes || [];
  90823. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  90824. }
  90825. };
  90826. var SceneSerializer = /** @class */ (function () {
  90827. function SceneSerializer() {
  90828. }
  90829. SceneSerializer.ClearCache = function () {
  90830. serializedGeometries = [];
  90831. };
  90832. SceneSerializer.Serialize = function (scene) {
  90833. var serializationObject = {};
  90834. SceneSerializer.ClearCache();
  90835. // Scene
  90836. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  90837. serializationObject.autoClear = scene.autoClear;
  90838. serializationObject.clearColor = scene.clearColor.asArray();
  90839. serializationObject.ambientColor = scene.ambientColor.asArray();
  90840. serializationObject.gravity = scene.gravity.asArray();
  90841. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  90842. serializationObject.workerCollisions = scene.workerCollisions;
  90843. // Fog
  90844. if (scene.fogMode && scene.fogMode !== 0) {
  90845. serializationObject.fogMode = scene.fogMode;
  90846. serializationObject.fogColor = scene.fogColor.asArray();
  90847. serializationObject.fogStart = scene.fogStart;
  90848. serializationObject.fogEnd = scene.fogEnd;
  90849. serializationObject.fogDensity = scene.fogDensity;
  90850. }
  90851. //Physics
  90852. if (scene.isPhysicsEnabled()) {
  90853. var physicEngine = scene.getPhysicsEngine();
  90854. if (physicEngine) {
  90855. serializationObject.physicsEnabled = true;
  90856. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  90857. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  90858. }
  90859. }
  90860. // Metadata
  90861. if (scene.metadata) {
  90862. serializationObject.metadata = scene.metadata;
  90863. }
  90864. // Morph targets
  90865. serializationObject.morphTargetManagers = [];
  90866. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  90867. var abstractMesh = _a[_i];
  90868. var manager = abstractMesh.morphTargetManager;
  90869. if (manager) {
  90870. serializationObject.morphTargetManagers.push(manager.serialize());
  90871. }
  90872. }
  90873. // Lights
  90874. serializationObject.lights = [];
  90875. var index;
  90876. var light;
  90877. for (index = 0; index < scene.lights.length; index++) {
  90878. light = scene.lights[index];
  90879. if (!light.doNotSerialize) {
  90880. serializationObject.lights.push(light.serialize());
  90881. }
  90882. }
  90883. // Cameras
  90884. serializationObject.cameras = [];
  90885. for (index = 0; index < scene.cameras.length; index++) {
  90886. var camera = scene.cameras[index];
  90887. if (!camera.doNotSerialize) {
  90888. serializationObject.cameras.push(camera.serialize());
  90889. }
  90890. }
  90891. if (scene.activeCamera) {
  90892. serializationObject.activeCameraID = scene.activeCamera.id;
  90893. }
  90894. // Animations
  90895. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  90896. // Materials
  90897. serializationObject.materials = [];
  90898. serializationObject.multiMaterials = [];
  90899. var material;
  90900. for (index = 0; index < scene.materials.length; index++) {
  90901. material = scene.materials[index];
  90902. if (!material.doNotSerialize) {
  90903. serializationObject.materials.push(material.serialize());
  90904. }
  90905. }
  90906. // MultiMaterials
  90907. serializationObject.multiMaterials = [];
  90908. for (index = 0; index < scene.multiMaterials.length; index++) {
  90909. var multiMaterial = scene.multiMaterials[index];
  90910. serializationObject.multiMaterials.push(multiMaterial.serialize());
  90911. }
  90912. // Environment texture
  90913. if (scene.environmentTexture) {
  90914. serializationObject.environmentTexture = scene.environmentTexture.name;
  90915. }
  90916. // Skeletons
  90917. serializationObject.skeletons = [];
  90918. for (index = 0; index < scene.skeletons.length; index++) {
  90919. var skeleton = scene.skeletons[index];
  90920. if (!skeleton.doNotSerialize) {
  90921. serializationObject.skeletons.push(skeleton.serialize());
  90922. }
  90923. }
  90924. // Transform nodes
  90925. serializationObject.transformNodes = [];
  90926. for (index = 0; index < scene.transformNodes.length; index++) {
  90927. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  90928. }
  90929. // Geometries
  90930. serializationObject.geometries = {};
  90931. serializationObject.geometries.boxes = [];
  90932. serializationObject.geometries.spheres = [];
  90933. serializationObject.geometries.cylinders = [];
  90934. serializationObject.geometries.toruses = [];
  90935. serializationObject.geometries.grounds = [];
  90936. serializationObject.geometries.planes = [];
  90937. serializationObject.geometries.torusKnots = [];
  90938. serializationObject.geometries.vertexData = [];
  90939. serializedGeometries = [];
  90940. var geometries = scene.getGeometries();
  90941. for (index = 0; index < geometries.length; index++) {
  90942. var geometry = geometries[index];
  90943. if (geometry.isReady()) {
  90944. serializeGeometry(geometry, serializationObject.geometries);
  90945. }
  90946. }
  90947. // Meshes
  90948. serializationObject.meshes = [];
  90949. for (index = 0; index < scene.meshes.length; index++) {
  90950. var abstractMesh = scene.meshes[index];
  90951. if (abstractMesh instanceof BABYLON.Mesh) {
  90952. var mesh = abstractMesh;
  90953. if (!mesh.doNotSerialize) {
  90954. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  90955. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  90956. }
  90957. }
  90958. }
  90959. }
  90960. // Particles Systems
  90961. serializationObject.particleSystems = [];
  90962. for (index = 0; index < scene.particleSystems.length; index++) {
  90963. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  90964. }
  90965. // Lens flares
  90966. serializationObject.lensFlareSystems = [];
  90967. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  90968. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  90969. }
  90970. // Shadows
  90971. serializationObject.shadowGenerators = [];
  90972. for (index = 0; index < scene.lights.length; index++) {
  90973. light = scene.lights[index];
  90974. var shadowGenerator = light.getShadowGenerator();
  90975. if (shadowGenerator) {
  90976. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  90977. }
  90978. }
  90979. // Action Manager
  90980. if (scene.actionManager) {
  90981. serializationObject.actions = scene.actionManager.serialize("scene");
  90982. }
  90983. // Audio
  90984. serializationObject.sounds = [];
  90985. for (index = 0; index < scene.soundTracks.length; index++) {
  90986. var soundtrack = scene.soundTracks[index];
  90987. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  90988. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  90989. }
  90990. }
  90991. return serializationObject;
  90992. };
  90993. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  90994. if (withParents === void 0) { withParents = false; }
  90995. if (withChildren === void 0) { withChildren = false; }
  90996. var serializationObject = {};
  90997. SceneSerializer.ClearCache();
  90998. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  90999. if (withParents || withChildren) {
  91000. //deliberate for loop! not for each, appended should be processed as well.
  91001. for (var i = 0; i < toSerialize.length; ++i) {
  91002. if (withChildren) {
  91003. toSerialize[i].getDescendants().forEach(function (node) {
  91004. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  91005. toSerialize.push(node);
  91006. }
  91007. });
  91008. }
  91009. //make sure the array doesn't contain the object already
  91010. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  91011. toSerialize.push(toSerialize[i].parent);
  91012. }
  91013. }
  91014. }
  91015. toSerialize.forEach(function (mesh) {
  91016. finalizeSingleMesh(mesh, serializationObject);
  91017. });
  91018. return serializationObject;
  91019. };
  91020. return SceneSerializer;
  91021. }());
  91022. BABYLON.SceneSerializer = SceneSerializer;
  91023. })(BABYLON || (BABYLON = {}));
  91024. //# sourceMappingURL=babylon.sceneSerializer.js.map
  91025. "use strict";
  91026. var BABYLON;
  91027. (function (BABYLON) {
  91028. var ReflectionProbe = /** @class */ (function () {
  91029. function ReflectionProbe(name, size, scene, generateMipMaps) {
  91030. if (generateMipMaps === void 0) { generateMipMaps = true; }
  91031. var _this = this;
  91032. this.name = name;
  91033. this._viewMatrix = BABYLON.Matrix.Identity();
  91034. this._target = BABYLON.Vector3.Zero();
  91035. this._add = BABYLON.Vector3.Zero();
  91036. this._invertYAxis = false;
  91037. this.position = BABYLON.Vector3.Zero();
  91038. this._scene = scene;
  91039. this._scene.reflectionProbes.push(this);
  91040. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  91041. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  91042. switch (faceIndex) {
  91043. case 0:
  91044. _this._add.copyFromFloats(1, 0, 0);
  91045. break;
  91046. case 1:
  91047. _this._add.copyFromFloats(-1, 0, 0);
  91048. break;
  91049. case 2:
  91050. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  91051. break;
  91052. case 3:
  91053. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  91054. break;
  91055. case 4:
  91056. _this._add.copyFromFloats(0, 0, 1);
  91057. break;
  91058. case 5:
  91059. _this._add.copyFromFloats(0, 0, -1);
  91060. break;
  91061. }
  91062. if (_this._attachedMesh) {
  91063. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  91064. }
  91065. _this.position.addToRef(_this._add, _this._target);
  91066. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  91067. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  91068. scene._forcedViewPosition = _this.position;
  91069. });
  91070. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  91071. scene._forcedViewPosition = null;
  91072. scene.updateTransformMatrix(true);
  91073. });
  91074. if (scene.activeCamera) {
  91075. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  91076. }
  91077. }
  91078. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  91079. get: function () {
  91080. return this._renderTargetTexture.samples;
  91081. },
  91082. set: function (value) {
  91083. this._renderTargetTexture.samples = value;
  91084. },
  91085. enumerable: true,
  91086. configurable: true
  91087. });
  91088. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  91089. get: function () {
  91090. return this._renderTargetTexture.refreshRate;
  91091. },
  91092. set: function (value) {
  91093. this._renderTargetTexture.refreshRate = value;
  91094. },
  91095. enumerable: true,
  91096. configurable: true
  91097. });
  91098. ReflectionProbe.prototype.getScene = function () {
  91099. return this._scene;
  91100. };
  91101. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  91102. get: function () {
  91103. return this._renderTargetTexture;
  91104. },
  91105. enumerable: true,
  91106. configurable: true
  91107. });
  91108. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  91109. get: function () {
  91110. return this._renderTargetTexture.renderList;
  91111. },
  91112. enumerable: true,
  91113. configurable: true
  91114. });
  91115. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  91116. this._attachedMesh = mesh;
  91117. };
  91118. /**
  91119. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  91120. *
  91121. * @param renderingGroupId The rendering group id corresponding to its index
  91122. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  91123. */
  91124. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  91125. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  91126. };
  91127. ReflectionProbe.prototype.dispose = function () {
  91128. var index = this._scene.reflectionProbes.indexOf(this);
  91129. if (index !== -1) {
  91130. // Remove from the scene if found
  91131. this._scene.reflectionProbes.splice(index, 1);
  91132. }
  91133. if (this._renderTargetTexture) {
  91134. this._renderTargetTexture.dispose();
  91135. this._renderTargetTexture = null;
  91136. }
  91137. };
  91138. return ReflectionProbe;
  91139. }());
  91140. BABYLON.ReflectionProbe = ReflectionProbe;
  91141. })(BABYLON || (BABYLON = {}));
  91142. //# sourceMappingURL=babylon.reflectionProbe.js.map
  91143. "use strict";
  91144. var BABYLON;
  91145. (function (BABYLON) {
  91146. var Layer = /** @class */ (function () {
  91147. function Layer(name, imgUrl, scene, isBackground, color) {
  91148. this.name = name;
  91149. this.scale = new BABYLON.Vector2(1, 1);
  91150. this.offset = new BABYLON.Vector2(0, 0);
  91151. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  91152. this.layerMask = 0x0FFFFFFF;
  91153. this._vertexBuffers = {};
  91154. // Events
  91155. /**
  91156. * An event triggered when the layer is disposed.
  91157. */
  91158. this.onDisposeObservable = new BABYLON.Observable();
  91159. /**
  91160. * An event triggered before rendering the scene
  91161. */
  91162. this.onBeforeRenderObservable = new BABYLON.Observable();
  91163. /**
  91164. * An event triggered after rendering the scene
  91165. */
  91166. this.onAfterRenderObservable = new BABYLON.Observable();
  91167. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  91168. this.isBackground = isBackground === undefined ? true : isBackground;
  91169. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  91170. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  91171. this._scene.layers.push(this);
  91172. var engine = this._scene.getEngine();
  91173. // VBO
  91174. var vertices = [];
  91175. vertices.push(1, 1);
  91176. vertices.push(-1, 1);
  91177. vertices.push(-1, -1);
  91178. vertices.push(1, -1);
  91179. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  91180. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  91181. this._createIndexBuffer();
  91182. // Effects
  91183. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  91184. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  91185. }
  91186. Object.defineProperty(Layer.prototype, "onDispose", {
  91187. set: function (callback) {
  91188. if (this._onDisposeObserver) {
  91189. this.onDisposeObservable.remove(this._onDisposeObserver);
  91190. }
  91191. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  91192. },
  91193. enumerable: true,
  91194. configurable: true
  91195. });
  91196. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  91197. set: function (callback) {
  91198. if (this._onBeforeRenderObserver) {
  91199. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  91200. }
  91201. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  91202. },
  91203. enumerable: true,
  91204. configurable: true
  91205. });
  91206. Object.defineProperty(Layer.prototype, "onAfterRender", {
  91207. set: function (callback) {
  91208. if (this._onAfterRenderObserver) {
  91209. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  91210. }
  91211. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  91212. },
  91213. enumerable: true,
  91214. configurable: true
  91215. });
  91216. Layer.prototype._createIndexBuffer = function () {
  91217. var engine = this._scene.getEngine();
  91218. // Indices
  91219. var indices = [];
  91220. indices.push(0);
  91221. indices.push(1);
  91222. indices.push(2);
  91223. indices.push(0);
  91224. indices.push(2);
  91225. indices.push(3);
  91226. this._indexBuffer = engine.createIndexBuffer(indices);
  91227. };
  91228. Layer.prototype._rebuild = function () {
  91229. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  91230. if (vb) {
  91231. vb._rebuild();
  91232. }
  91233. this._createIndexBuffer();
  91234. };
  91235. Layer.prototype.render = function () {
  91236. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  91237. // Check
  91238. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  91239. return;
  91240. var engine = this._scene.getEngine();
  91241. this.onBeforeRenderObservable.notifyObservers(this);
  91242. // Render
  91243. engine.enableEffect(currentEffect);
  91244. engine.setState(false);
  91245. // Texture
  91246. currentEffect.setTexture("textureSampler", this.texture);
  91247. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  91248. // Color
  91249. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  91250. // Scale / offset
  91251. currentEffect.setVector2("offset", this.offset);
  91252. currentEffect.setVector2("scale", this.scale);
  91253. // VBOs
  91254. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  91255. // Draw order
  91256. if (!this.alphaTest) {
  91257. engine.setAlphaMode(this.alphaBlendingMode);
  91258. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  91259. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  91260. }
  91261. else {
  91262. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  91263. }
  91264. this.onAfterRenderObservable.notifyObservers(this);
  91265. };
  91266. Layer.prototype.dispose = function () {
  91267. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  91268. if (vertexBuffer) {
  91269. vertexBuffer.dispose();
  91270. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  91271. }
  91272. if (this._indexBuffer) {
  91273. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  91274. this._indexBuffer = null;
  91275. }
  91276. if (this.texture) {
  91277. this.texture.dispose();
  91278. this.texture = null;
  91279. }
  91280. // Remove from scene
  91281. var index = this._scene.layers.indexOf(this);
  91282. this._scene.layers.splice(index, 1);
  91283. // Callback
  91284. this.onDisposeObservable.notifyObservers(this);
  91285. this.onDisposeObservable.clear();
  91286. this.onAfterRenderObservable.clear();
  91287. this.onBeforeRenderObservable.clear();
  91288. };
  91289. return Layer;
  91290. }());
  91291. BABYLON.Layer = Layer;
  91292. })(BABYLON || (BABYLON = {}));
  91293. //# sourceMappingURL=babylon.layer.js.map
  91294. "use strict";
  91295. var BABYLON;
  91296. (function (BABYLON) {
  91297. var TextureTools = /** @class */ (function () {
  91298. function TextureTools() {
  91299. }
  91300. /**
  91301. * Uses the GPU to create a copy texture rescaled at a given size
  91302. * @param texture Texture to copy from
  91303. * @param width Desired width
  91304. * @param height Desired height
  91305. * @return Generated texture
  91306. */
  91307. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  91308. if (useBilinearMode === void 0) { useBilinearMode = true; }
  91309. var scene = texture.getScene();
  91310. var engine = scene.getEngine();
  91311. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  91312. rtt.wrapU = texture.wrapU;
  91313. rtt.wrapV = texture.wrapV;
  91314. rtt.uOffset = texture.uOffset;
  91315. rtt.vOffset = texture.vOffset;
  91316. rtt.uScale = texture.uScale;
  91317. rtt.vScale = texture.vScale;
  91318. rtt.uAng = texture.uAng;
  91319. rtt.vAng = texture.vAng;
  91320. rtt.wAng = texture.wAng;
  91321. rtt.coordinatesIndex = texture.coordinatesIndex;
  91322. rtt.level = texture.level;
  91323. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  91324. rtt._texture.isReady = false;
  91325. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91326. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91327. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  91328. passPostProcess.getEffect().executeWhenCompiled(function () {
  91329. passPostProcess.onApply = function (effect) {
  91330. effect.setTexture("textureSampler", texture);
  91331. };
  91332. var internalTexture = rtt.getInternalTexture();
  91333. if (internalTexture) {
  91334. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  91335. engine.unBindFramebuffer(internalTexture);
  91336. rtt.disposeFramebufferObjects();
  91337. passPostProcess.dispose();
  91338. internalTexture.isReady = true;
  91339. }
  91340. });
  91341. return rtt;
  91342. };
  91343. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  91344. if (!scene._environmentBRDFTexture) {
  91345. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  91346. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91347. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91348. scene._environmentBRDFTexture = texture;
  91349. }
  91350. return scene._environmentBRDFTexture;
  91351. };
  91352. 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=";
  91353. return TextureTools;
  91354. }());
  91355. BABYLON.TextureTools = TextureTools;
  91356. })(BABYLON || (BABYLON = {}));
  91357. //# sourceMappingURL=babylon.textureTools.js.map
  91358. "use strict";
  91359. var BABYLON;
  91360. (function (BABYLON) {
  91361. var FramingBehavior = /** @class */ (function () {
  91362. function FramingBehavior() {
  91363. this._mode = FramingBehavior.FitFrustumSidesMode;
  91364. this._radiusScale = 1.0;
  91365. this._positionScale = 0.5;
  91366. this._defaultElevation = 0.3;
  91367. this._elevationReturnTime = 1500;
  91368. this._elevationReturnWaitTime = 1000;
  91369. this._zoomStopsAnimation = false;
  91370. this._framingTime = 1500;
  91371. this._isPointerDown = false;
  91372. this._lastInteractionTime = -Infinity;
  91373. // Framing control
  91374. this._animatables = new Array();
  91375. this._betaIsAnimating = false;
  91376. }
  91377. Object.defineProperty(FramingBehavior.prototype, "name", {
  91378. get: function () {
  91379. return "Framing";
  91380. },
  91381. enumerable: true,
  91382. configurable: true
  91383. });
  91384. Object.defineProperty(FramingBehavior.prototype, "mode", {
  91385. /**
  91386. * Gets current mode used by the behavior.
  91387. */
  91388. get: function () {
  91389. return this._mode;
  91390. },
  91391. /**
  91392. * Sets the current mode used by the behavior
  91393. */
  91394. set: function (mode) {
  91395. this._mode = mode;
  91396. },
  91397. enumerable: true,
  91398. configurable: true
  91399. });
  91400. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  91401. /**
  91402. * Gets the scale applied to the radius
  91403. */
  91404. get: function () {
  91405. return this._radiusScale;
  91406. },
  91407. /**
  91408. * Sets the scale applied to the radius (1 by default)
  91409. */
  91410. set: function (radius) {
  91411. this._radiusScale = radius;
  91412. },
  91413. enumerable: true,
  91414. configurable: true
  91415. });
  91416. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  91417. /**
  91418. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  91419. */
  91420. get: function () {
  91421. return this._positionScale;
  91422. },
  91423. /**
  91424. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  91425. */
  91426. set: function (scale) {
  91427. this._positionScale = scale;
  91428. },
  91429. enumerable: true,
  91430. configurable: true
  91431. });
  91432. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  91433. /**
  91434. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  91435. * behaviour is triggered, in radians.
  91436. */
  91437. get: function () {
  91438. return this._defaultElevation;
  91439. },
  91440. /**
  91441. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  91442. * behaviour is triggered, in radians.
  91443. */
  91444. set: function (elevation) {
  91445. this._defaultElevation = elevation;
  91446. },
  91447. enumerable: true,
  91448. configurable: true
  91449. });
  91450. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  91451. /**
  91452. * Gets the time (in milliseconds) taken to return to the default beta position.
  91453. * Negative value indicates camera should not return to default.
  91454. */
  91455. get: function () {
  91456. return this._elevationReturnTime;
  91457. },
  91458. /**
  91459. * Sets the time (in milliseconds) taken to return to the default beta position.
  91460. * Negative value indicates camera should not return to default.
  91461. */
  91462. set: function (speed) {
  91463. this._elevationReturnTime = speed;
  91464. },
  91465. enumerable: true,
  91466. configurable: true
  91467. });
  91468. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  91469. /**
  91470. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  91471. */
  91472. get: function () {
  91473. return this._elevationReturnWaitTime;
  91474. },
  91475. /**
  91476. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  91477. */
  91478. set: function (time) {
  91479. this._elevationReturnWaitTime = time;
  91480. },
  91481. enumerable: true,
  91482. configurable: true
  91483. });
  91484. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  91485. /**
  91486. * Gets the flag that indicates if user zooming should stop animation.
  91487. */
  91488. get: function () {
  91489. return this._zoomStopsAnimation;
  91490. },
  91491. /**
  91492. * Sets the flag that indicates if user zooming should stop animation.
  91493. */
  91494. set: function (flag) {
  91495. this._zoomStopsAnimation = flag;
  91496. },
  91497. enumerable: true,
  91498. configurable: true
  91499. });
  91500. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  91501. /**
  91502. * Gets the transition time when framing the mesh, in milliseconds
  91503. */
  91504. get: function () {
  91505. return this._framingTime;
  91506. },
  91507. /**
  91508. * Sets the transition time when framing the mesh, in milliseconds
  91509. */
  91510. set: function (time) {
  91511. this._framingTime = time;
  91512. },
  91513. enumerable: true,
  91514. configurable: true
  91515. });
  91516. FramingBehavior.prototype.init = function () {
  91517. // Do notihng
  91518. };
  91519. FramingBehavior.prototype.attach = function (camera) {
  91520. var _this = this;
  91521. this._attachedCamera = camera;
  91522. var scene = this._attachedCamera.getScene();
  91523. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  91524. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  91525. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  91526. _this._isPointerDown = true;
  91527. return;
  91528. }
  91529. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  91530. _this._isPointerDown = false;
  91531. }
  91532. });
  91533. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  91534. if (mesh) {
  91535. _this.zoomOnMesh(mesh);
  91536. }
  91537. });
  91538. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  91539. // Stop the animation if there is user interaction and the animation should stop for this interaction
  91540. _this._applyUserInteraction();
  91541. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  91542. // back to the default position after a given timeout
  91543. _this._maintainCameraAboveGround();
  91544. });
  91545. };
  91546. FramingBehavior.prototype.detach = function () {
  91547. if (!this._attachedCamera) {
  91548. return;
  91549. }
  91550. var scene = this._attachedCamera.getScene();
  91551. if (this._onPrePointerObservableObserver) {
  91552. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  91553. }
  91554. if (this._onAfterCheckInputsObserver) {
  91555. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  91556. }
  91557. if (this._onMeshTargetChangedObserver) {
  91558. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  91559. }
  91560. this._attachedCamera = null;
  91561. };
  91562. /**
  91563. * Targets the given mesh and updates zoom level accordingly.
  91564. * @param mesh The mesh to target.
  91565. * @param radius Optional. If a cached radius position already exists, overrides default.
  91566. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  91567. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  91568. * @param onAnimationEnd Callback triggered at the end of the framing animation
  91569. */
  91570. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  91571. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  91572. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  91573. mesh.computeWorldMatrix(true);
  91574. var boundingBox = mesh.getBoundingInfo().boundingBox;
  91575. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  91576. };
  91577. /**
  91578. * Targets the given mesh with its children and updates zoom level accordingly.
  91579. * @param mesh The mesh to target.
  91580. * @param radius Optional. If a cached radius position already exists, overrides default.
  91581. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  91582. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  91583. * @param onAnimationEnd Callback triggered at the end of the framing animation
  91584. */
  91585. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  91586. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  91587. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  91588. mesh.computeWorldMatrix(true);
  91589. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  91590. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  91591. };
  91592. /**
  91593. * Targets the given meshes with their children and updates zoom level accordingly.
  91594. * @param meshes The mesh to target.
  91595. * @param radius Optional. If a cached radius position already exists, overrides default.
  91596. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  91597. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  91598. * @param onAnimationEnd Callback triggered at the end of the framing animation
  91599. */
  91600. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  91601. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  91602. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  91603. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  91604. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  91605. for (var i = 0; i < meshes.length; i++) {
  91606. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  91607. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  91608. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  91609. }
  91610. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  91611. };
  91612. /**
  91613. * Targets the given mesh and updates zoom level accordingly.
  91614. * @param mesh The mesh to target.
  91615. * @param radius Optional. If a cached radius position already exists, overrides default.
  91616. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  91617. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  91618. * @param onAnimationEnd Callback triggered at the end of the framing animation
  91619. */
  91620. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  91621. var _this = this;
  91622. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  91623. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  91624. var zoomTarget;
  91625. if (!this._attachedCamera) {
  91626. return;
  91627. }
  91628. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  91629. var bottom = minimumWorld.y;
  91630. var top = maximumWorld.y;
  91631. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  91632. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  91633. if (focusOnOriginXZ) {
  91634. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  91635. }
  91636. else {
  91637. var centerWorld = minimumWorld.add(radiusWorld);
  91638. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  91639. }
  91640. if (!this._vectorTransition) {
  91641. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  91642. }
  91643. this._betaIsAnimating = true;
  91644. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  91645. if (animatable) {
  91646. this._animatables.push(animatable);
  91647. }
  91648. // sets the radius and lower radius bounds
  91649. // Small delta ensures camera is not always at lower zoom limit.
  91650. var radius = 0;
  91651. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  91652. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  91653. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  91654. radius = position;
  91655. }
  91656. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  91657. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  91658. if (this._attachedCamera.lowerRadiusLimit === null) {
  91659. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  91660. }
  91661. }
  91662. // Set sensibilities
  91663. var extend = maximumWorld.subtract(minimumWorld).length();
  91664. this._attachedCamera.panningSensibility = 5000 / extend;
  91665. this._attachedCamera.wheelPrecision = 100 / radius;
  91666. // transition to new radius
  91667. if (!this._radiusTransition) {
  91668. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  91669. }
  91670. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  91671. _this.stopAllAnimations();
  91672. if (onAnimationEnd) {
  91673. onAnimationEnd();
  91674. }
  91675. if (_this._attachedCamera) {
  91676. _this._attachedCamera.storeState();
  91677. }
  91678. });
  91679. if (animatable) {
  91680. this._animatables.push(animatable);
  91681. }
  91682. };
  91683. /**
  91684. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  91685. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  91686. * frustum width.
  91687. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  91688. * to fully enclose the mesh in the viewing frustum.
  91689. */
  91690. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  91691. var size = maximumWorld.subtract(minimumWorld);
  91692. var boxVectorGlobalDiagonal = size.length();
  91693. var frustumSlope = this._getFrustumSlope();
  91694. // Formula for setting distance
  91695. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  91696. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  91697. // Horizon distance
  91698. var radius = radiusWithoutFraming * this._radiusScale;
  91699. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  91700. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  91701. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  91702. var camera = this._attachedCamera;
  91703. if (!camera) {
  91704. return 0;
  91705. }
  91706. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  91707. // Don't exceed the requested limit
  91708. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  91709. }
  91710. // Don't exceed the upper radius limit
  91711. if (camera.upperRadiusLimit) {
  91712. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  91713. }
  91714. return distance;
  91715. };
  91716. /**
  91717. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  91718. * is automatically returned to its default position (expected to be above ground plane).
  91719. */
  91720. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  91721. var _this = this;
  91722. if (this._elevationReturnTime < 0) {
  91723. return;
  91724. }
  91725. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  91726. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  91727. var limitBeta = Math.PI * 0.5;
  91728. // Bring the camera back up if below the ground plane
  91729. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  91730. this._betaIsAnimating = true;
  91731. //Transition to new position
  91732. this.stopAllAnimations();
  91733. if (!this._betaTransition) {
  91734. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  91735. }
  91736. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  91737. _this._clearAnimationLocks();
  91738. _this.stopAllAnimations();
  91739. });
  91740. if (animatabe) {
  91741. this._animatables.push(animatabe);
  91742. }
  91743. }
  91744. };
  91745. /**
  91746. * Returns the frustum slope based on the canvas ratio and camera FOV
  91747. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  91748. */
  91749. FramingBehavior.prototype._getFrustumSlope = function () {
  91750. // Calculate the viewport ratio
  91751. // Aspect Ratio is Height/Width.
  91752. var camera = this._attachedCamera;
  91753. if (!camera) {
  91754. return BABYLON.Vector2.Zero();
  91755. }
  91756. var engine = camera.getScene().getEngine();
  91757. var aspectRatio = engine.getAspectRatio(camera);
  91758. // Camera FOV is the vertical field of view (top-bottom) in radians.
  91759. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  91760. var frustumSlopeY = Math.tan(camera.fov / 2);
  91761. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  91762. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  91763. // along the forward vector.
  91764. var frustumSlopeX = frustumSlopeY * aspectRatio;
  91765. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  91766. };
  91767. /**
  91768. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  91769. */
  91770. FramingBehavior.prototype._clearAnimationLocks = function () {
  91771. this._betaIsAnimating = false;
  91772. };
  91773. /**
  91774. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  91775. */
  91776. FramingBehavior.prototype._applyUserInteraction = function () {
  91777. if (this.isUserIsMoving) {
  91778. this._lastInteractionTime = BABYLON.Tools.Now;
  91779. this.stopAllAnimations();
  91780. this._clearAnimationLocks();
  91781. }
  91782. };
  91783. /**
  91784. * Stops and removes all animations that have been applied to the camera
  91785. */
  91786. FramingBehavior.prototype.stopAllAnimations = function () {
  91787. if (this._attachedCamera) {
  91788. this._attachedCamera.animations = [];
  91789. }
  91790. while (this._animatables.length) {
  91791. if (this._animatables[0]) {
  91792. this._animatables[0].onAnimationEnd = null;
  91793. this._animatables[0].stop();
  91794. }
  91795. this._animatables.shift();
  91796. }
  91797. };
  91798. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  91799. /**
  91800. * Gets a value indicating if the user is moving the camera
  91801. */
  91802. get: function () {
  91803. if (!this._attachedCamera) {
  91804. return false;
  91805. }
  91806. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  91807. this._attachedCamera.inertialBetaOffset !== 0 ||
  91808. this._attachedCamera.inertialRadiusOffset !== 0 ||
  91809. this._attachedCamera.inertialPanningX !== 0 ||
  91810. this._attachedCamera.inertialPanningY !== 0 ||
  91811. this._isPointerDown;
  91812. },
  91813. enumerable: true,
  91814. configurable: true
  91815. });
  91816. /**
  91817. * The easing function used by animations
  91818. */
  91819. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  91820. /**
  91821. * The easing mode used by animations
  91822. */
  91823. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  91824. // Statics
  91825. /**
  91826. * The camera can move all the way towards the mesh.
  91827. */
  91828. FramingBehavior.IgnoreBoundsSizeMode = 0;
  91829. /**
  91830. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  91831. */
  91832. FramingBehavior.FitFrustumSidesMode = 1;
  91833. return FramingBehavior;
  91834. }());
  91835. BABYLON.FramingBehavior = FramingBehavior;
  91836. })(BABYLON || (BABYLON = {}));
  91837. //# sourceMappingURL=babylon.framingBehavior.js.map
  91838. "use strict";
  91839. var BABYLON;
  91840. (function (BABYLON) {
  91841. /**
  91842. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  91843. */
  91844. var BouncingBehavior = /** @class */ (function () {
  91845. function BouncingBehavior() {
  91846. /**
  91847. * The duration of the animation, in milliseconds
  91848. */
  91849. this.transitionDuration = 450;
  91850. /**
  91851. * Length of the distance animated by the transition when lower radius is reached
  91852. */
  91853. this.lowerRadiusTransitionRange = 2;
  91854. /**
  91855. * Length of the distance animated by the transition when upper radius is reached
  91856. */
  91857. this.upperRadiusTransitionRange = -2;
  91858. this._autoTransitionRange = false;
  91859. // Animations
  91860. this._radiusIsAnimating = false;
  91861. this._radiusBounceTransition = null;
  91862. this._animatables = new Array();
  91863. }
  91864. Object.defineProperty(BouncingBehavior.prototype, "name", {
  91865. get: function () {
  91866. return "Bouncing";
  91867. },
  91868. enumerable: true,
  91869. configurable: true
  91870. });
  91871. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  91872. /**
  91873. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  91874. */
  91875. get: function () {
  91876. return this._autoTransitionRange;
  91877. },
  91878. /**
  91879. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  91880. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  91881. */
  91882. set: function (value) {
  91883. var _this = this;
  91884. if (this._autoTransitionRange === value) {
  91885. return;
  91886. }
  91887. this._autoTransitionRange = value;
  91888. var camera = this._attachedCamera;
  91889. if (!camera) {
  91890. return;
  91891. }
  91892. if (value) {
  91893. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  91894. if (!mesh) {
  91895. return;
  91896. }
  91897. mesh.computeWorldMatrix(true);
  91898. var diagonal = mesh.getBoundingInfo().diagonalLength;
  91899. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  91900. _this.upperRadiusTransitionRange = diagonal * 0.05;
  91901. });
  91902. }
  91903. else if (this._onMeshTargetChangedObserver) {
  91904. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  91905. }
  91906. },
  91907. enumerable: true,
  91908. configurable: true
  91909. });
  91910. BouncingBehavior.prototype.init = function () {
  91911. // Do notihng
  91912. };
  91913. BouncingBehavior.prototype.attach = function (camera) {
  91914. var _this = this;
  91915. this._attachedCamera = camera;
  91916. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  91917. if (!_this._attachedCamera) {
  91918. return;
  91919. }
  91920. // Add the bounce animation to the lower radius limit
  91921. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  91922. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  91923. }
  91924. // Add the bounce animation to the upper radius limit
  91925. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  91926. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  91927. }
  91928. });
  91929. };
  91930. BouncingBehavior.prototype.detach = function () {
  91931. if (!this._attachedCamera) {
  91932. return;
  91933. }
  91934. if (this._onAfterCheckInputsObserver) {
  91935. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  91936. }
  91937. if (this._onMeshTargetChangedObserver) {
  91938. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  91939. }
  91940. this._attachedCamera = null;
  91941. };
  91942. /**
  91943. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  91944. * @param radiusLimit The limit to check against.
  91945. * @return Bool to indicate if at limit.
  91946. */
  91947. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  91948. if (!this._attachedCamera) {
  91949. return false;
  91950. }
  91951. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  91952. return true;
  91953. }
  91954. return false;
  91955. };
  91956. /**
  91957. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  91958. * @param radiusDelta The delta by which to animate to. Can be negative.
  91959. */
  91960. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  91961. var _this = this;
  91962. if (!this._attachedCamera) {
  91963. return;
  91964. }
  91965. if (!this._radiusBounceTransition) {
  91966. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  91967. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  91968. }
  91969. // Prevent zoom until bounce has completed
  91970. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  91971. this._attachedCamera.wheelPrecision = Infinity;
  91972. this._attachedCamera.inertialRadiusOffset = 0;
  91973. // Animate to the radius limit
  91974. this.stopAllAnimations();
  91975. this._radiusIsAnimating = true;
  91976. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  91977. if (animatable) {
  91978. this._animatables.push(animatable);
  91979. }
  91980. };
  91981. /**
  91982. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  91983. */
  91984. BouncingBehavior.prototype._clearAnimationLocks = function () {
  91985. this._radiusIsAnimating = false;
  91986. if (this._attachedCamera) {
  91987. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  91988. }
  91989. };
  91990. /**
  91991. * Stops and removes all animations that have been applied to the camera
  91992. */
  91993. BouncingBehavior.prototype.stopAllAnimations = function () {
  91994. if (this._attachedCamera) {
  91995. this._attachedCamera.animations = [];
  91996. }
  91997. while (this._animatables.length) {
  91998. this._animatables[0].onAnimationEnd = null;
  91999. this._animatables[0].stop();
  92000. this._animatables.shift();
  92001. }
  92002. };
  92003. /**
  92004. * The easing function used by animations
  92005. */
  92006. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  92007. /**
  92008. * The easing mode used by animations
  92009. */
  92010. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  92011. return BouncingBehavior;
  92012. }());
  92013. BABYLON.BouncingBehavior = BouncingBehavior;
  92014. })(BABYLON || (BABYLON = {}));
  92015. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  92016. "use strict";
  92017. var BABYLON;
  92018. (function (BABYLON) {
  92019. var AutoRotationBehavior = /** @class */ (function () {
  92020. function AutoRotationBehavior() {
  92021. this._zoomStopsAnimation = false;
  92022. this._idleRotationSpeed = 0.05;
  92023. this._idleRotationWaitTime = 2000;
  92024. this._idleRotationSpinupTime = 2000;
  92025. this._isPointerDown = false;
  92026. this._lastFrameTime = null;
  92027. this._lastInteractionTime = -Infinity;
  92028. this._cameraRotationSpeed = 0;
  92029. this._lastFrameRadius = 0;
  92030. }
  92031. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  92032. get: function () {
  92033. return "AutoRotation";
  92034. },
  92035. enumerable: true,
  92036. configurable: true
  92037. });
  92038. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  92039. /**
  92040. * Gets the flag that indicates if user zooming should stop animation.
  92041. */
  92042. get: function () {
  92043. return this._zoomStopsAnimation;
  92044. },
  92045. /**
  92046. * Sets the flag that indicates if user zooming should stop animation.
  92047. */
  92048. set: function (flag) {
  92049. this._zoomStopsAnimation = flag;
  92050. },
  92051. enumerable: true,
  92052. configurable: true
  92053. });
  92054. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  92055. /**
  92056. * Gets the default speed at which the camera rotates around the model.
  92057. */
  92058. get: function () {
  92059. return this._idleRotationSpeed;
  92060. },
  92061. /**
  92062. * Sets the default speed at which the camera rotates around the model.
  92063. */
  92064. set: function (speed) {
  92065. this._idleRotationSpeed = speed;
  92066. },
  92067. enumerable: true,
  92068. configurable: true
  92069. });
  92070. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  92071. /**
  92072. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  92073. */
  92074. get: function () {
  92075. return this._idleRotationWaitTime;
  92076. },
  92077. /**
  92078. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  92079. */
  92080. set: function (time) {
  92081. this._idleRotationWaitTime = time;
  92082. },
  92083. enumerable: true,
  92084. configurable: true
  92085. });
  92086. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  92087. /**
  92088. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  92089. */
  92090. get: function () {
  92091. return this._idleRotationSpinupTime;
  92092. },
  92093. /**
  92094. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  92095. */
  92096. set: function (time) {
  92097. this._idleRotationSpinupTime = time;
  92098. },
  92099. enumerable: true,
  92100. configurable: true
  92101. });
  92102. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  92103. /**
  92104. * Gets a value indicating if the camera is currently rotating because of this behavior
  92105. */
  92106. get: function () {
  92107. return Math.abs(this._cameraRotationSpeed) > 0;
  92108. },
  92109. enumerable: true,
  92110. configurable: true
  92111. });
  92112. AutoRotationBehavior.prototype.init = function () {
  92113. // Do notihng
  92114. };
  92115. AutoRotationBehavior.prototype.attach = function (camera) {
  92116. var _this = this;
  92117. this._attachedCamera = camera;
  92118. var scene = this._attachedCamera.getScene();
  92119. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  92120. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  92121. _this._isPointerDown = true;
  92122. return;
  92123. }
  92124. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  92125. _this._isPointerDown = false;
  92126. }
  92127. });
  92128. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  92129. var now = BABYLON.Tools.Now;
  92130. var dt = 0;
  92131. if (_this._lastFrameTime != null) {
  92132. dt = now - _this._lastFrameTime;
  92133. }
  92134. _this._lastFrameTime = now;
  92135. // Stop the animation if there is user interaction and the animation should stop for this interaction
  92136. _this._applyUserInteraction();
  92137. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  92138. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  92139. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  92140. // Step camera rotation by rotation speed
  92141. if (_this._attachedCamera) {
  92142. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  92143. }
  92144. });
  92145. };
  92146. AutoRotationBehavior.prototype.detach = function () {
  92147. if (!this._attachedCamera) {
  92148. return;
  92149. }
  92150. var scene = this._attachedCamera.getScene();
  92151. if (this._onPrePointerObservableObserver) {
  92152. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  92153. }
  92154. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  92155. this._attachedCamera = null;
  92156. };
  92157. /**
  92158. * Returns true if user is scrolling.
  92159. * @return true if user is scrolling.
  92160. */
  92161. AutoRotationBehavior.prototype._userIsZooming = function () {
  92162. if (!this._attachedCamera) {
  92163. return false;
  92164. }
  92165. return this._attachedCamera.inertialRadiusOffset !== 0;
  92166. };
  92167. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  92168. if (!this._attachedCamera) {
  92169. return false;
  92170. }
  92171. var zoomHasHitLimit = false;
  92172. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  92173. zoomHasHitLimit = true;
  92174. }
  92175. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  92176. this._lastFrameRadius = this._attachedCamera.radius;
  92177. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  92178. };
  92179. /**
  92180. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  92181. */
  92182. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  92183. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  92184. this._lastInteractionTime = BABYLON.Tools.Now;
  92185. }
  92186. };
  92187. // Tools
  92188. AutoRotationBehavior.prototype._userIsMoving = function () {
  92189. if (!this._attachedCamera) {
  92190. return false;
  92191. }
  92192. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  92193. this._attachedCamera.inertialBetaOffset !== 0 ||
  92194. this._attachedCamera.inertialRadiusOffset !== 0 ||
  92195. this._attachedCamera.inertialPanningX !== 0 ||
  92196. this._attachedCamera.inertialPanningY !== 0 ||
  92197. this._isPointerDown;
  92198. };
  92199. return AutoRotationBehavior;
  92200. }());
  92201. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  92202. })(BABYLON || (BABYLON = {}));
  92203. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  92204. "use strict";
  92205. var BABYLON;
  92206. (function (BABYLON) {
  92207. var NullEngineOptions = /** @class */ (function () {
  92208. function NullEngineOptions() {
  92209. this.renderWidth = 512;
  92210. this.renderHeight = 256;
  92211. this.textureSize = 512;
  92212. this.deterministicLockstep = false;
  92213. this.lockstepMaxSteps = 4;
  92214. }
  92215. return NullEngineOptions;
  92216. }());
  92217. BABYLON.NullEngineOptions = NullEngineOptions;
  92218. /**
  92219. * The null engine class provides support for headless version of babylon.js.
  92220. * This can be used in server side scenario or for testing purposes
  92221. */
  92222. var NullEngine = /** @class */ (function (_super) {
  92223. __extends(NullEngine, _super);
  92224. function NullEngine(options) {
  92225. if (options === void 0) { options = new NullEngineOptions(); }
  92226. var _this = _super.call(this, null) || this;
  92227. if (options.deterministicLockstep === undefined) {
  92228. options.deterministicLockstep = false;
  92229. }
  92230. if (options.lockstepMaxSteps === undefined) {
  92231. options.lockstepMaxSteps = 4;
  92232. }
  92233. _this._options = options;
  92234. // Init caps
  92235. // We consider we are on a webgl1 capable device
  92236. _this._caps = new BABYLON.EngineCapabilities();
  92237. _this._caps.maxTexturesImageUnits = 16;
  92238. _this._caps.maxVertexTextureImageUnits = 16;
  92239. _this._caps.maxTextureSize = 512;
  92240. _this._caps.maxCubemapTextureSize = 512;
  92241. _this._caps.maxRenderTextureSize = 512;
  92242. _this._caps.maxVertexAttribs = 16;
  92243. _this._caps.maxVaryingVectors = 16;
  92244. _this._caps.maxFragmentUniformVectors = 16;
  92245. _this._caps.maxVertexUniformVectors = 16;
  92246. // Extensions
  92247. _this._caps.standardDerivatives = false;
  92248. _this._caps.astc = null;
  92249. _this._caps.s3tc = null;
  92250. _this._caps.pvrtc = null;
  92251. _this._caps.etc1 = null;
  92252. _this._caps.etc2 = null;
  92253. _this._caps.textureAnisotropicFilterExtension = null;
  92254. _this._caps.maxAnisotropy = 0;
  92255. _this._caps.uintIndices = false;
  92256. _this._caps.fragmentDepthSupported = false;
  92257. _this._caps.highPrecisionShaderSupported = true;
  92258. _this._caps.colorBufferFloat = false;
  92259. _this._caps.textureFloat = false;
  92260. _this._caps.textureFloatLinearFiltering = false;
  92261. _this._caps.textureFloatRender = false;
  92262. _this._caps.textureHalfFloat = false;
  92263. _this._caps.textureHalfFloatLinearFiltering = false;
  92264. _this._caps.textureHalfFloatRender = false;
  92265. _this._caps.textureLOD = false;
  92266. _this._caps.drawBuffersExtension = false;
  92267. _this._caps.depthTextureExtension = false;
  92268. _this._caps.vertexArrayObject = false;
  92269. _this._caps.instancedArrays = false;
  92270. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  92271. // Wrappers
  92272. if (typeof URL === "undefined") {
  92273. URL = {
  92274. createObjectURL: function () { },
  92275. revokeObjectURL: function () { }
  92276. };
  92277. }
  92278. if (typeof Blob === "undefined") {
  92279. Blob = function () { };
  92280. }
  92281. return _this;
  92282. }
  92283. NullEngine.prototype.isDeterministicLockStep = function () {
  92284. return this._options.deterministicLockstep;
  92285. };
  92286. NullEngine.prototype.getLockstepMaxSteps = function () {
  92287. return this._options.lockstepMaxSteps;
  92288. };
  92289. NullEngine.prototype.getHardwareScalingLevel = function () {
  92290. return 1.0;
  92291. };
  92292. NullEngine.prototype.createVertexBuffer = function (vertices) {
  92293. return {
  92294. capacity: 0,
  92295. references: 1,
  92296. is32Bits: false
  92297. };
  92298. };
  92299. NullEngine.prototype.createIndexBuffer = function (indices) {
  92300. return {
  92301. capacity: 0,
  92302. references: 1,
  92303. is32Bits: false
  92304. };
  92305. };
  92306. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  92307. if (stencil === void 0) { stencil = false; }
  92308. };
  92309. NullEngine.prototype.getRenderWidth = function (useScreen) {
  92310. if (useScreen === void 0) { useScreen = false; }
  92311. if (!useScreen && this._currentRenderTarget) {
  92312. return this._currentRenderTarget.width;
  92313. }
  92314. return this._options.renderWidth;
  92315. };
  92316. NullEngine.prototype.getRenderHeight = function (useScreen) {
  92317. if (useScreen === void 0) { useScreen = false; }
  92318. if (!useScreen && this._currentRenderTarget) {
  92319. return this._currentRenderTarget.height;
  92320. }
  92321. return this._options.renderHeight;
  92322. };
  92323. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  92324. this._cachedViewport = viewport;
  92325. };
  92326. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  92327. return {
  92328. transformFeedback: null,
  92329. __SPECTOR_rebuildProgram: null
  92330. };
  92331. };
  92332. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  92333. return [];
  92334. };
  92335. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  92336. return [];
  92337. };
  92338. NullEngine.prototype.bindSamplers = function (effect) {
  92339. this._currentEffect = null;
  92340. };
  92341. NullEngine.prototype.enableEffect = function (effect) {
  92342. this._currentEffect = effect;
  92343. if (effect.onBind) {
  92344. effect.onBind(effect);
  92345. }
  92346. effect.onBindObservable.notifyObservers(effect);
  92347. };
  92348. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  92349. if (zOffset === void 0) { zOffset = 0; }
  92350. if (reverseSide === void 0) { reverseSide = false; }
  92351. };
  92352. NullEngine.prototype.setIntArray = function (uniform, array) {
  92353. };
  92354. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  92355. };
  92356. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  92357. };
  92358. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  92359. };
  92360. NullEngine.prototype.setFloatArray = function (uniform, array) {
  92361. };
  92362. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  92363. };
  92364. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  92365. };
  92366. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  92367. };
  92368. NullEngine.prototype.setArray = function (uniform, array) {
  92369. };
  92370. NullEngine.prototype.setArray2 = function (uniform, array) {
  92371. };
  92372. NullEngine.prototype.setArray3 = function (uniform, array) {
  92373. };
  92374. NullEngine.prototype.setArray4 = function (uniform, array) {
  92375. };
  92376. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  92377. };
  92378. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  92379. };
  92380. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  92381. };
  92382. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  92383. };
  92384. NullEngine.prototype.setFloat = function (uniform, value) {
  92385. };
  92386. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  92387. };
  92388. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  92389. };
  92390. NullEngine.prototype.setBool = function (uniform, bool) {
  92391. };
  92392. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  92393. };
  92394. NullEngine.prototype.setColor3 = function (uniform, color3) {
  92395. };
  92396. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  92397. };
  92398. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  92399. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  92400. if (this._alphaMode === mode) {
  92401. return;
  92402. }
  92403. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  92404. if (!noDepthWriteChange) {
  92405. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  92406. }
  92407. this._alphaMode = mode;
  92408. };
  92409. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  92410. };
  92411. NullEngine.prototype.wipeCaches = function (bruteForce) {
  92412. if (this.preventCacheWipeBetweenFrames) {
  92413. return;
  92414. }
  92415. this.resetTextureCache();
  92416. this._currentEffect = null;
  92417. if (bruteForce) {
  92418. this._currentProgram = null;
  92419. this._stencilState.reset();
  92420. this._depthCullingState.reset();
  92421. this._alphaState.reset();
  92422. }
  92423. this._cachedVertexBuffers = null;
  92424. this._cachedIndexBuffer = null;
  92425. this._cachedEffectForVertexBuffers = null;
  92426. };
  92427. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  92428. };
  92429. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  92430. };
  92431. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  92432. };
  92433. NullEngine.prototype._createTexture = function () {
  92434. return {};
  92435. };
  92436. NullEngine.prototype._releaseTexture = function (texture) {
  92437. };
  92438. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  92439. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  92440. if (onLoad === void 0) { onLoad = null; }
  92441. if (onError === void 0) { onError = null; }
  92442. if (buffer === void 0) { buffer = null; }
  92443. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  92444. var url = String(urlArg);
  92445. texture.url = url;
  92446. texture.generateMipMaps = !noMipmap;
  92447. texture.samplingMode = samplingMode;
  92448. texture.invertY = invertY;
  92449. texture.baseWidth = this._options.textureSize;
  92450. texture.baseHeight = this._options.textureSize;
  92451. texture.width = this._options.textureSize;
  92452. texture.height = this._options.textureSize;
  92453. if (format) {
  92454. texture.format = format;
  92455. }
  92456. texture.isReady = true;
  92457. if (onLoad) {
  92458. onLoad();
  92459. }
  92460. return texture;
  92461. };
  92462. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  92463. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  92464. if (options !== undefined && typeof options === "object") {
  92465. fullOptions.generateMipMaps = options.generateMipMaps;
  92466. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  92467. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  92468. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  92469. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  92470. }
  92471. else {
  92472. fullOptions.generateMipMaps = options;
  92473. fullOptions.generateDepthBuffer = true;
  92474. fullOptions.generateStencilBuffer = false;
  92475. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  92476. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  92477. }
  92478. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  92479. var width = size.width || size;
  92480. var height = size.height || size;
  92481. texture._depthStencilBuffer = {};
  92482. texture._framebuffer = {};
  92483. texture.baseWidth = width;
  92484. texture.baseHeight = height;
  92485. texture.width = width;
  92486. texture.height = height;
  92487. texture.isReady = true;
  92488. texture.samples = 1;
  92489. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  92490. texture.samplingMode = fullOptions.samplingMode;
  92491. texture.type = fullOptions.type;
  92492. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  92493. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  92494. return texture;
  92495. };
  92496. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  92497. texture.samplingMode = samplingMode;
  92498. };
  92499. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  92500. if (this._currentRenderTarget) {
  92501. this.unBindFramebuffer(this._currentRenderTarget);
  92502. }
  92503. this._currentRenderTarget = texture;
  92504. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  92505. if (this._cachedViewport && !forceFullscreenViewport) {
  92506. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  92507. }
  92508. };
  92509. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  92510. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  92511. this._currentRenderTarget = null;
  92512. if (onBeforeUnbind) {
  92513. if (texture._MSAAFramebuffer) {
  92514. this._currentFramebuffer = texture._framebuffer;
  92515. }
  92516. onBeforeUnbind();
  92517. }
  92518. this._currentFramebuffer = null;
  92519. };
  92520. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  92521. var vbo = {
  92522. capacity: 1,
  92523. references: 1,
  92524. is32Bits: false
  92525. };
  92526. return vbo;
  92527. };
  92528. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  92529. if (offset === void 0) { offset = 0; }
  92530. };
  92531. /**
  92532. * Updates a dynamic vertex buffer.
  92533. * @param vertexBuffer the vertex buffer to update
  92534. * @param data the data used to update the vertex buffer
  92535. * @param byteOffset the byte offset of the data (optional)
  92536. * @param byteLength the byte length of the data (optional)
  92537. */
  92538. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  92539. };
  92540. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  92541. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  92542. this._boundTexturesCache[this._activeChannel] = texture;
  92543. }
  92544. };
  92545. NullEngine.prototype._bindTexture = function (channel, texture) {
  92546. if (channel < 0) {
  92547. return;
  92548. }
  92549. this._bindTextureDirectly(0, texture);
  92550. };
  92551. NullEngine.prototype._releaseBuffer = function (buffer) {
  92552. buffer.references--;
  92553. if (buffer.references === 0) {
  92554. return true;
  92555. }
  92556. return false;
  92557. };
  92558. return NullEngine;
  92559. }(BABYLON.Engine));
  92560. BABYLON.NullEngine = NullEngine;
  92561. })(BABYLON || (BABYLON = {}));
  92562. //# sourceMappingURL=babylon.nullEngine.js.map
  92563. "use strict";
  92564. var BABYLON;
  92565. (function (BABYLON) {
  92566. /**
  92567. * This class can be used to get instrumentation data from a Babylon engine
  92568. */
  92569. var EngineInstrumentation = /** @class */ (function () {
  92570. function EngineInstrumentation(engine) {
  92571. this.engine = engine;
  92572. this._captureGPUFrameTime = false;
  92573. this._gpuFrameTime = new BABYLON.PerfCounter();
  92574. this._captureShaderCompilationTime = false;
  92575. this._shaderCompilationTime = new BABYLON.PerfCounter();
  92576. // Observers
  92577. this._onBeginFrameObserver = null;
  92578. this._onEndFrameObserver = null;
  92579. this._onBeforeShaderCompilationObserver = null;
  92580. this._onAfterShaderCompilationObserver = null;
  92581. }
  92582. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  92583. // Properties
  92584. /**
  92585. * Gets the perf counter used for GPU frame time
  92586. */
  92587. get: function () {
  92588. return this._gpuFrameTime;
  92589. },
  92590. enumerable: true,
  92591. configurable: true
  92592. });
  92593. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  92594. /**
  92595. * Gets the GPU frame time capture status
  92596. */
  92597. get: function () {
  92598. return this._captureGPUFrameTime;
  92599. },
  92600. /**
  92601. * Enable or disable the GPU frame time capture
  92602. */
  92603. set: function (value) {
  92604. var _this = this;
  92605. if (value === this._captureGPUFrameTime) {
  92606. return;
  92607. }
  92608. this._captureGPUFrameTime = value;
  92609. if (value) {
  92610. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  92611. if (!_this._gpuFrameTimeToken) {
  92612. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  92613. }
  92614. });
  92615. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  92616. if (!_this._gpuFrameTimeToken) {
  92617. return;
  92618. }
  92619. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  92620. if (time > -1) {
  92621. _this._gpuFrameTimeToken = null;
  92622. _this._gpuFrameTime.fetchNewFrame();
  92623. _this._gpuFrameTime.addCount(time, true);
  92624. }
  92625. });
  92626. }
  92627. else {
  92628. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  92629. this._onBeginFrameObserver = null;
  92630. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  92631. this._onEndFrameObserver = null;
  92632. }
  92633. },
  92634. enumerable: true,
  92635. configurable: true
  92636. });
  92637. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  92638. /**
  92639. * Gets the perf counter used for shader compilation time
  92640. */
  92641. get: function () {
  92642. return this._shaderCompilationTime;
  92643. },
  92644. enumerable: true,
  92645. configurable: true
  92646. });
  92647. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  92648. /**
  92649. * Gets the shader compilation time capture status
  92650. */
  92651. get: function () {
  92652. return this._captureShaderCompilationTime;
  92653. },
  92654. /**
  92655. * Enable or disable the shader compilation time capture
  92656. */
  92657. set: function (value) {
  92658. var _this = this;
  92659. if (value === this._captureShaderCompilationTime) {
  92660. return;
  92661. }
  92662. this._captureShaderCompilationTime = value;
  92663. if (value) {
  92664. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  92665. _this._shaderCompilationTime.fetchNewFrame();
  92666. _this._shaderCompilationTime.beginMonitoring();
  92667. });
  92668. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  92669. _this._shaderCompilationTime.endMonitoring();
  92670. });
  92671. }
  92672. else {
  92673. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  92674. this._onBeforeShaderCompilationObserver = null;
  92675. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  92676. this._onAfterShaderCompilationObserver = null;
  92677. }
  92678. },
  92679. enumerable: true,
  92680. configurable: true
  92681. });
  92682. EngineInstrumentation.prototype.dispose = function () {
  92683. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  92684. this._onBeginFrameObserver = null;
  92685. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  92686. this._onEndFrameObserver = null;
  92687. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  92688. this._onBeforeShaderCompilationObserver = null;
  92689. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  92690. this._onAfterShaderCompilationObserver = null;
  92691. this.engine = null;
  92692. };
  92693. return EngineInstrumentation;
  92694. }());
  92695. BABYLON.EngineInstrumentation = EngineInstrumentation;
  92696. })(BABYLON || (BABYLON = {}));
  92697. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  92698. "use strict";
  92699. var BABYLON;
  92700. (function (BABYLON) {
  92701. /**
  92702. * This class can be used to get instrumentation data from a Babylon engine
  92703. */
  92704. var SceneInstrumentation = /** @class */ (function () {
  92705. function SceneInstrumentation(scene) {
  92706. var _this = this;
  92707. this.scene = scene;
  92708. this._captureActiveMeshesEvaluationTime = false;
  92709. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  92710. this._captureRenderTargetsRenderTime = false;
  92711. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  92712. this._captureFrameTime = false;
  92713. this._frameTime = new BABYLON.PerfCounter();
  92714. this._captureRenderTime = false;
  92715. this._renderTime = new BABYLON.PerfCounter();
  92716. this._captureInterFrameTime = false;
  92717. this._interFrameTime = new BABYLON.PerfCounter();
  92718. this._captureParticlesRenderTime = false;
  92719. this._particlesRenderTime = new BABYLON.PerfCounter();
  92720. this._captureSpritesRenderTime = false;
  92721. this._spritesRenderTime = new BABYLON.PerfCounter();
  92722. this._capturePhysicsTime = false;
  92723. this._physicsTime = new BABYLON.PerfCounter();
  92724. this._captureAnimationsTime = false;
  92725. this._animationsTime = new BABYLON.PerfCounter();
  92726. // Observers
  92727. this._onBeforeActiveMeshesEvaluationObserver = null;
  92728. this._onAfterActiveMeshesEvaluationObserver = null;
  92729. this._onBeforeRenderTargetsRenderObserver = null;
  92730. this._onAfterRenderTargetsRenderObserver = null;
  92731. this._onAfterRenderObserver = null;
  92732. this._onBeforeDrawPhaseObserver = null;
  92733. this._onAfterDrawPhaseObserver = null;
  92734. this._onBeforeAnimationsObserver = null;
  92735. this._onBeforeParticlesRenderingObserver = null;
  92736. this._onAfterParticlesRenderingObserver = null;
  92737. this._onBeforeSpritesRenderingObserver = null;
  92738. this._onAfterSpritesRenderingObserver = null;
  92739. this._onBeforePhysicsObserver = null;
  92740. this._onAfterPhysicsObserver = null;
  92741. this._onAfterAnimationsObserver = null;
  92742. // Before render
  92743. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  92744. if (_this._captureActiveMeshesEvaluationTime) {
  92745. _this._activeMeshesEvaluationTime.fetchNewFrame();
  92746. }
  92747. if (_this._captureRenderTargetsRenderTime) {
  92748. _this._renderTargetsRenderTime.fetchNewFrame();
  92749. }
  92750. if (_this._captureFrameTime) {
  92751. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  92752. _this._frameTime.beginMonitoring();
  92753. }
  92754. if (_this._captureInterFrameTime) {
  92755. _this._interFrameTime.endMonitoring();
  92756. }
  92757. if (_this._captureParticlesRenderTime) {
  92758. _this._particlesRenderTime.fetchNewFrame();
  92759. }
  92760. if (_this._captureSpritesRenderTime) {
  92761. _this._spritesRenderTime.fetchNewFrame();
  92762. }
  92763. if (_this._captureAnimationsTime) {
  92764. _this._animationsTime.beginMonitoring();
  92765. }
  92766. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  92767. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  92768. });
  92769. // After render
  92770. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  92771. if (_this._captureFrameTime) {
  92772. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  92773. _this._frameTime.endMonitoring();
  92774. }
  92775. if (_this._captureRenderTime) {
  92776. _this._renderTime.endMonitoring(false);
  92777. }
  92778. if (_this._captureInterFrameTime) {
  92779. _this._interFrameTime.beginMonitoring();
  92780. }
  92781. });
  92782. }
  92783. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  92784. // Properties
  92785. /**
  92786. * Gets the perf counter used for active meshes evaluation time
  92787. */
  92788. get: function () {
  92789. return this._activeMeshesEvaluationTime;
  92790. },
  92791. enumerable: true,
  92792. configurable: true
  92793. });
  92794. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  92795. /**
  92796. * Gets the active meshes evaluation time capture status
  92797. */
  92798. get: function () {
  92799. return this._captureActiveMeshesEvaluationTime;
  92800. },
  92801. /**
  92802. * Enable or disable the active meshes evaluation time capture
  92803. */
  92804. set: function (value) {
  92805. var _this = this;
  92806. if (value === this._captureActiveMeshesEvaluationTime) {
  92807. return;
  92808. }
  92809. this._captureActiveMeshesEvaluationTime = value;
  92810. if (value) {
  92811. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  92812. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  92813. _this._activeMeshesEvaluationTime.beginMonitoring();
  92814. });
  92815. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  92816. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  92817. _this._activeMeshesEvaluationTime.endMonitoring();
  92818. });
  92819. }
  92820. else {
  92821. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  92822. this._onBeforeActiveMeshesEvaluationObserver = null;
  92823. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  92824. this._onAfterActiveMeshesEvaluationObserver = null;
  92825. }
  92826. },
  92827. enumerable: true,
  92828. configurable: true
  92829. });
  92830. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  92831. /**
  92832. * Gets the perf counter used for render targets render time
  92833. */
  92834. get: function () {
  92835. return this._renderTargetsRenderTime;
  92836. },
  92837. enumerable: true,
  92838. configurable: true
  92839. });
  92840. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  92841. /**
  92842. * Gets the render targets render time capture status
  92843. */
  92844. get: function () {
  92845. return this._captureRenderTargetsRenderTime;
  92846. },
  92847. /**
  92848. * Enable or disable the render targets render time capture
  92849. */
  92850. set: function (value) {
  92851. var _this = this;
  92852. if (value === this._captureRenderTargetsRenderTime) {
  92853. return;
  92854. }
  92855. this._captureRenderTargetsRenderTime = value;
  92856. if (value) {
  92857. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  92858. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  92859. _this._renderTargetsRenderTime.beginMonitoring();
  92860. });
  92861. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  92862. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  92863. _this._renderTargetsRenderTime.endMonitoring(false);
  92864. });
  92865. }
  92866. else {
  92867. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  92868. this._onBeforeRenderTargetsRenderObserver = null;
  92869. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  92870. this._onAfterRenderTargetsRenderObserver = null;
  92871. }
  92872. },
  92873. enumerable: true,
  92874. configurable: true
  92875. });
  92876. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  92877. /**
  92878. * Gets the perf counter used for particles render time
  92879. */
  92880. get: function () {
  92881. return this._particlesRenderTime;
  92882. },
  92883. enumerable: true,
  92884. configurable: true
  92885. });
  92886. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  92887. /**
  92888. * Gets the particles render time capture status
  92889. */
  92890. get: function () {
  92891. return this._captureParticlesRenderTime;
  92892. },
  92893. /**
  92894. * Enable or disable the particles render time capture
  92895. */
  92896. set: function (value) {
  92897. var _this = this;
  92898. if (value === this._captureParticlesRenderTime) {
  92899. return;
  92900. }
  92901. this._captureParticlesRenderTime = value;
  92902. if (value) {
  92903. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  92904. BABYLON.Tools.StartPerformanceCounter("Particles");
  92905. _this._particlesRenderTime.beginMonitoring();
  92906. });
  92907. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  92908. BABYLON.Tools.EndPerformanceCounter("Particles");
  92909. _this._particlesRenderTime.endMonitoring(false);
  92910. });
  92911. }
  92912. else {
  92913. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  92914. this._onBeforeParticlesRenderingObserver = null;
  92915. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  92916. this._onAfterParticlesRenderingObserver = null;
  92917. }
  92918. },
  92919. enumerable: true,
  92920. configurable: true
  92921. });
  92922. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  92923. /**
  92924. * Gets the perf counter used for sprites render time
  92925. */
  92926. get: function () {
  92927. return this._spritesRenderTime;
  92928. },
  92929. enumerable: true,
  92930. configurable: true
  92931. });
  92932. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  92933. /**
  92934. * Gets the sprites render time capture status
  92935. */
  92936. get: function () {
  92937. return this._captureSpritesRenderTime;
  92938. },
  92939. /**
  92940. * Enable or disable the sprites render time capture
  92941. */
  92942. set: function (value) {
  92943. var _this = this;
  92944. if (value === this._captureSpritesRenderTime) {
  92945. return;
  92946. }
  92947. this._captureSpritesRenderTime = value;
  92948. if (value) {
  92949. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  92950. BABYLON.Tools.StartPerformanceCounter("Sprites");
  92951. _this._spritesRenderTime.beginMonitoring();
  92952. });
  92953. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  92954. BABYLON.Tools.EndPerformanceCounter("Sprites");
  92955. _this._spritesRenderTime.endMonitoring(false);
  92956. });
  92957. }
  92958. else {
  92959. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  92960. this._onBeforeSpritesRenderingObserver = null;
  92961. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  92962. this._onAfterSpritesRenderingObserver = null;
  92963. }
  92964. },
  92965. enumerable: true,
  92966. configurable: true
  92967. });
  92968. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  92969. /**
  92970. * Gets the perf counter used for physics time
  92971. */
  92972. get: function () {
  92973. return this._physicsTime;
  92974. },
  92975. enumerable: true,
  92976. configurable: true
  92977. });
  92978. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  92979. /**
  92980. * Gets the physics time capture status
  92981. */
  92982. get: function () {
  92983. return this._capturePhysicsTime;
  92984. },
  92985. /**
  92986. * Enable or disable the physics time capture
  92987. */
  92988. set: function (value) {
  92989. var _this = this;
  92990. if (value === this._capturePhysicsTime) {
  92991. return;
  92992. }
  92993. this._capturePhysicsTime = value;
  92994. if (value) {
  92995. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  92996. BABYLON.Tools.StartPerformanceCounter("Physics");
  92997. _this._physicsTime.beginMonitoring();
  92998. });
  92999. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  93000. BABYLON.Tools.EndPerformanceCounter("Physics");
  93001. _this._physicsTime.endMonitoring();
  93002. });
  93003. }
  93004. else {
  93005. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  93006. this._onBeforePhysicsObserver = null;
  93007. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  93008. this._onAfterPhysicsObserver = null;
  93009. }
  93010. },
  93011. enumerable: true,
  93012. configurable: true
  93013. });
  93014. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  93015. /**
  93016. * Gets the perf counter used for animations time
  93017. */
  93018. get: function () {
  93019. return this._animationsTime;
  93020. },
  93021. enumerable: true,
  93022. configurable: true
  93023. });
  93024. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  93025. /**
  93026. * Gets the animations time capture status
  93027. */
  93028. get: function () {
  93029. return this._captureAnimationsTime;
  93030. },
  93031. /**
  93032. * Enable or disable the animations time capture
  93033. */
  93034. set: function (value) {
  93035. var _this = this;
  93036. if (value === this._captureAnimationsTime) {
  93037. return;
  93038. }
  93039. this._captureAnimationsTime = value;
  93040. if (value) {
  93041. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  93042. _this._animationsTime.endMonitoring();
  93043. });
  93044. }
  93045. else {
  93046. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  93047. this._onAfterAnimationsObserver = null;
  93048. }
  93049. },
  93050. enumerable: true,
  93051. configurable: true
  93052. });
  93053. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  93054. /**
  93055. * Gets the perf counter used for frame time capture
  93056. */
  93057. get: function () {
  93058. return this._frameTime;
  93059. },
  93060. enumerable: true,
  93061. configurable: true
  93062. });
  93063. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  93064. /**
  93065. * Gets the frame time capture status
  93066. */
  93067. get: function () {
  93068. return this._captureFrameTime;
  93069. },
  93070. /**
  93071. * Enable or disable the frame time capture
  93072. */
  93073. set: function (value) {
  93074. this._captureFrameTime = value;
  93075. },
  93076. enumerable: true,
  93077. configurable: true
  93078. });
  93079. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  93080. /**
  93081. * Gets the perf counter used for inter-frames time capture
  93082. */
  93083. get: function () {
  93084. return this._interFrameTime;
  93085. },
  93086. enumerable: true,
  93087. configurable: true
  93088. });
  93089. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  93090. /**
  93091. * Gets the inter-frames time capture status
  93092. */
  93093. get: function () {
  93094. return this._captureInterFrameTime;
  93095. },
  93096. /**
  93097. * Enable or disable the inter-frames time capture
  93098. */
  93099. set: function (value) {
  93100. this._captureInterFrameTime = value;
  93101. },
  93102. enumerable: true,
  93103. configurable: true
  93104. });
  93105. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  93106. /**
  93107. * Gets the perf counter used for render time capture
  93108. */
  93109. get: function () {
  93110. return this._renderTime;
  93111. },
  93112. enumerable: true,
  93113. configurable: true
  93114. });
  93115. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  93116. /**
  93117. * Gets the render time capture status
  93118. */
  93119. get: function () {
  93120. return this._captureRenderTime;
  93121. },
  93122. /**
  93123. * Enable or disable the render time capture
  93124. */
  93125. set: function (value) {
  93126. var _this = this;
  93127. if (value === this._captureRenderTime) {
  93128. return;
  93129. }
  93130. this._captureRenderTime = value;
  93131. if (value) {
  93132. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  93133. _this._renderTime.beginMonitoring();
  93134. BABYLON.Tools.StartPerformanceCounter("Main render");
  93135. });
  93136. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  93137. _this._renderTime.endMonitoring(false);
  93138. BABYLON.Tools.EndPerformanceCounter("Main render");
  93139. });
  93140. }
  93141. else {
  93142. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  93143. this._onBeforeDrawPhaseObserver = null;
  93144. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  93145. this._onAfterDrawPhaseObserver = null;
  93146. }
  93147. },
  93148. enumerable: true,
  93149. configurable: true
  93150. });
  93151. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  93152. /**
  93153. * Gets the perf counter used for draw calls
  93154. */
  93155. get: function () {
  93156. return this.scene.getEngine()._drawCalls;
  93157. },
  93158. enumerable: true,
  93159. configurable: true
  93160. });
  93161. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  93162. /**
  93163. * Gets the perf counter used for texture collisions
  93164. */
  93165. get: function () {
  93166. return this.scene.getEngine()._textureCollisions;
  93167. },
  93168. enumerable: true,
  93169. configurable: true
  93170. });
  93171. SceneInstrumentation.prototype.dispose = function () {
  93172. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  93173. this._onAfterRenderObserver = null;
  93174. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  93175. this._onBeforeActiveMeshesEvaluationObserver = null;
  93176. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  93177. this._onAfterActiveMeshesEvaluationObserver = null;
  93178. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  93179. this._onBeforeRenderTargetsRenderObserver = null;
  93180. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  93181. this._onAfterRenderTargetsRenderObserver = null;
  93182. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  93183. this._onBeforeAnimationsObserver = null;
  93184. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  93185. this._onBeforeParticlesRenderingObserver = null;
  93186. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  93187. this._onAfterParticlesRenderingObserver = null;
  93188. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  93189. this._onBeforeSpritesRenderingObserver = null;
  93190. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  93191. this._onAfterSpritesRenderingObserver = null;
  93192. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  93193. this._onBeforeDrawPhaseObserver = null;
  93194. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  93195. this._onAfterDrawPhaseObserver = null;
  93196. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  93197. this._onBeforePhysicsObserver = null;
  93198. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  93199. this._onAfterPhysicsObserver = null;
  93200. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  93201. this._onAfterAnimationsObserver = null;
  93202. this.scene = null;
  93203. };
  93204. return SceneInstrumentation;
  93205. }());
  93206. BABYLON.SceneInstrumentation = SceneInstrumentation;
  93207. })(BABYLON || (BABYLON = {}));
  93208. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  93209. "use strict";
  93210. var BABYLON;
  93211. (function (BABYLON) {
  93212. var _TimeToken = /** @class */ (function () {
  93213. function _TimeToken() {
  93214. this._timeElapsedQueryEnded = false;
  93215. }
  93216. return _TimeToken;
  93217. }());
  93218. BABYLON._TimeToken = _TimeToken;
  93219. })(BABYLON || (BABYLON = {}));
  93220. //# sourceMappingURL=babylon.timeToken.js.map
  93221. "use strict";
  93222. var BABYLON;
  93223. (function (BABYLON) {
  93224. /**
  93225. * Background material defines definition.
  93226. * @ignore Mainly internal Use
  93227. */
  93228. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  93229. __extends(BackgroundMaterialDefines, _super);
  93230. /**
  93231. * Constructor of the defines.
  93232. */
  93233. function BackgroundMaterialDefines() {
  93234. var _this = _super.call(this) || this;
  93235. /**
  93236. * True if the diffuse texture is in use.
  93237. */
  93238. _this.DIFFUSE = false;
  93239. /**
  93240. * The direct UV channel to use.
  93241. */
  93242. _this.DIFFUSEDIRECTUV = 0;
  93243. /**
  93244. * True if the diffuse texture is in gamma space.
  93245. */
  93246. _this.GAMMADIFFUSE = false;
  93247. /**
  93248. * True if the diffuse texture has opacity in the alpha channel.
  93249. */
  93250. _this.DIFFUSEHASALPHA = false;
  93251. /**
  93252. * True if you want the material to fade to transparent at grazing angle.
  93253. */
  93254. _this.OPACITYFRESNEL = false;
  93255. /**
  93256. * True if an extra blur needs to be added in the reflection.
  93257. */
  93258. _this.REFLECTIONBLUR = false;
  93259. /**
  93260. * True if you want the material to fade to reflection at grazing angle.
  93261. */
  93262. _this.REFLECTIONFRESNEL = false;
  93263. /**
  93264. * True if you want the material to falloff as far as you move away from the scene center.
  93265. */
  93266. _this.REFLECTIONFALLOFF = false;
  93267. /**
  93268. * False if the current Webgl implementation does not support the texture lod extension.
  93269. */
  93270. _this.TEXTURELODSUPPORT = false;
  93271. /**
  93272. * True to ensure the data are premultiplied.
  93273. */
  93274. _this.PREMULTIPLYALPHA = false;
  93275. /**
  93276. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  93277. */
  93278. _this.USERGBCOLOR = false;
  93279. /**
  93280. * True to add noise in order to reduce the banding effect.
  93281. */
  93282. _this.NOISE = false;
  93283. /**
  93284. * is the reflection texture in BGR color scheme?
  93285. * Mainly used to solve a bug in ios10 video tag
  93286. */
  93287. _this.REFLECTIONBGR = false;
  93288. _this.IMAGEPROCESSING = false;
  93289. _this.VIGNETTE = false;
  93290. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  93291. _this.VIGNETTEBLENDMODEOPAQUE = false;
  93292. _this.TONEMAPPING = false;
  93293. _this.CONTRAST = false;
  93294. _this.COLORCURVES = false;
  93295. _this.COLORGRADING = false;
  93296. _this.COLORGRADING3D = false;
  93297. _this.SAMPLER3DGREENDEPTH = false;
  93298. _this.SAMPLER3DBGRMAP = false;
  93299. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  93300. _this.EXPOSURE = false;
  93301. // Reflection.
  93302. _this.REFLECTION = false;
  93303. _this.REFLECTIONMAP_3D = false;
  93304. _this.REFLECTIONMAP_SPHERICAL = false;
  93305. _this.REFLECTIONMAP_PLANAR = false;
  93306. _this.REFLECTIONMAP_CUBIC = false;
  93307. _this.REFLECTIONMAP_PROJECTION = false;
  93308. _this.REFLECTIONMAP_SKYBOX = false;
  93309. _this.REFLECTIONMAP_EXPLICIT = false;
  93310. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  93311. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  93312. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  93313. _this.INVERTCUBICMAP = false;
  93314. _this.REFLECTIONMAP_OPPOSITEZ = false;
  93315. _this.LODINREFLECTIONALPHA = false;
  93316. _this.GAMMAREFLECTION = false;
  93317. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  93318. // Default BJS.
  93319. _this.MAINUV1 = false;
  93320. _this.MAINUV2 = false;
  93321. _this.UV1 = false;
  93322. _this.UV2 = false;
  93323. _this.CLIPPLANE = false;
  93324. _this.POINTSIZE = false;
  93325. _this.FOG = false;
  93326. _this.NORMAL = false;
  93327. _this.NUM_BONE_INFLUENCERS = 0;
  93328. _this.BonesPerMesh = 0;
  93329. _this.INSTANCES = false;
  93330. _this.SHADOWFLOAT = false;
  93331. _this.rebuild();
  93332. return _this;
  93333. }
  93334. return BackgroundMaterialDefines;
  93335. }(BABYLON.MaterialDefines));
  93336. /**
  93337. * Background material used to create an efficient environement around your scene.
  93338. */
  93339. var BackgroundMaterial = /** @class */ (function (_super) {
  93340. __extends(BackgroundMaterial, _super);
  93341. /**
  93342. * Instantiates a Background Material in the given scene
  93343. * @param name The friendly name of the material
  93344. * @param scene The scene to add the material to
  93345. */
  93346. function BackgroundMaterial(name, scene) {
  93347. var _this = _super.call(this, name, scene) || this;
  93348. /**
  93349. * Key light Color (multiply against the R channel of the environement texture)
  93350. */
  93351. _this.primaryColor = BABYLON.Color3.White();
  93352. /**
  93353. * Key light Level (allowing HDR output of the background)
  93354. */
  93355. _this.primaryLevel = 1;
  93356. /**
  93357. * Secondary light Color (multiply against the G channel of the environement texture)
  93358. */
  93359. _this.secondaryColor = BABYLON.Color3.Gray();
  93360. /**
  93361. * Secondary light Level (allowing HDR output of the background)
  93362. */
  93363. _this.secondaryLevel = 1;
  93364. /**
  93365. * Tertiary light Color (multiply against the B channel of the environement texture)
  93366. */
  93367. _this.tertiaryColor = BABYLON.Color3.Black();
  93368. /**
  93369. * Tertiary light Level (allowing HDR output of the background)
  93370. */
  93371. _this.tertiaryLevel = 1;
  93372. /**
  93373. * Reflection Texture used in the material.
  93374. * Should be author in a specific way for the best result (refer to the documentation).
  93375. */
  93376. _this.reflectionTexture = null;
  93377. /**
  93378. * Reflection Texture level of blur.
  93379. *
  93380. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  93381. * texture twice.
  93382. */
  93383. _this.reflectionBlur = 0;
  93384. /**
  93385. * Diffuse Texture used in the material.
  93386. * Should be author in a specific way for the best result (refer to the documentation).
  93387. */
  93388. _this.diffuseTexture = null;
  93389. _this._shadowLights = null;
  93390. /**
  93391. * Specify the list of lights casting shadow on the material.
  93392. * All scene shadow lights will be included if null.
  93393. */
  93394. _this.shadowLights = null;
  93395. /**
  93396. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  93397. * soft lighting on the background.
  93398. */
  93399. _this.shadowBlurScale = 1;
  93400. /**
  93401. * Helps adjusting the shadow to a softer level if required.
  93402. * 0 means black shadows and 1 means no shadows.
  93403. */
  93404. _this.shadowLevel = 0;
  93405. /**
  93406. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  93407. * It is usually zero but might be interesting to modify according to your setup.
  93408. */
  93409. _this.sceneCenter = BABYLON.Vector3.Zero();
  93410. /**
  93411. * This helps specifying that the material is falling off to the sky box at grazing angle.
  93412. * This helps ensuring a nice transition when the camera goes under the ground.
  93413. */
  93414. _this.opacityFresnel = true;
  93415. /**
  93416. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  93417. * This helps adding a mirror texture on the ground.
  93418. */
  93419. _this.reflectionFresnel = false;
  93420. /**
  93421. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  93422. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  93423. */
  93424. _this.reflectionFalloffDistance = 0.0;
  93425. /**
  93426. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  93427. */
  93428. _this.reflectionAmount = 1.0;
  93429. /**
  93430. * This specifies the weight of the reflection at grazing angle.
  93431. */
  93432. _this.reflectionReflectance0 = 0.05;
  93433. /**
  93434. * This specifies the weight of the reflection at a perpendicular point of view.
  93435. */
  93436. _this.reflectionReflectance90 = 0.5;
  93437. /**
  93438. * Helps to directly use the maps channels instead of their level.
  93439. */
  93440. _this.useRGBColor = true;
  93441. /**
  93442. * This helps reducing the banding effect that could occur on the background.
  93443. */
  93444. _this.enableNoise = false;
  93445. _this._fovMultiplier = 1.0;
  93446. /**
  93447. * Enable the FOV adjustment feature controlled by fovMultiplier.
  93448. */
  93449. _this.useEquirectangularFOV = false;
  93450. _this._maxSimultaneousLights = 4;
  93451. /**
  93452. * Number of Simultaneous lights allowed on the material.
  93453. */
  93454. _this.maxSimultaneousLights = 4;
  93455. /**
  93456. * Keep track of the image processing observer to allow dispose and replace.
  93457. */
  93458. _this._imageProcessingObserver = null;
  93459. /**
  93460. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  93461. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  93462. */
  93463. _this.switchToBGR = false;
  93464. // Temp values kept as cache in the material.
  93465. _this._renderTargets = new BABYLON.SmartArray(16);
  93466. _this._reflectionControls = BABYLON.Vector4.Zero();
  93467. // Setup the default processing configuration to the scene.
  93468. _this._attachImageProcessingConfiguration(null);
  93469. _this.getRenderTargetTextures = function () {
  93470. _this._renderTargets.reset();
  93471. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  93472. _this._renderTargets.push(_this._diffuseTexture);
  93473. }
  93474. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  93475. _this._renderTargets.push(_this._reflectionTexture);
  93476. }
  93477. return _this._renderTargets;
  93478. };
  93479. return _this;
  93480. }
  93481. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  93482. /**
  93483. * Sets the reflection reflectance fresnel values according to the default standard
  93484. * empirically know to work well :-)
  93485. */
  93486. set: function (value) {
  93487. var reflectionWeight = value;
  93488. if (reflectionWeight < 0.5) {
  93489. reflectionWeight = reflectionWeight * 2.0;
  93490. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  93491. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  93492. }
  93493. else {
  93494. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  93495. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  93496. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  93497. }
  93498. },
  93499. enumerable: true,
  93500. configurable: true
  93501. });
  93502. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  93503. /**
  93504. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  93505. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  93506. * Recommended to be keep at 1.0 except for special cases.
  93507. */
  93508. get: function () {
  93509. return this._fovMultiplier;
  93510. },
  93511. set: function (value) {
  93512. if (isNaN(value)) {
  93513. value = 1.0;
  93514. }
  93515. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  93516. },
  93517. enumerable: true,
  93518. configurable: true
  93519. });
  93520. /**
  93521. * Attaches a new image processing configuration to the PBR Material.
  93522. * @param configuration (if null the scene configuration will be use)
  93523. */
  93524. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  93525. var _this = this;
  93526. if (configuration === this._imageProcessingConfiguration) {
  93527. return;
  93528. }
  93529. // Detaches observer.
  93530. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  93531. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  93532. }
  93533. // Pick the scene configuration if needed.
  93534. if (!configuration) {
  93535. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  93536. }
  93537. else {
  93538. this._imageProcessingConfiguration = configuration;
  93539. }
  93540. // Attaches observer.
  93541. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  93542. _this._markAllSubMeshesAsImageProcessingDirty();
  93543. });
  93544. };
  93545. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  93546. /**
  93547. * Gets the image processing configuration used either in this material.
  93548. */
  93549. get: function () {
  93550. return this._imageProcessingConfiguration;
  93551. },
  93552. /**
  93553. * Sets the Default image processing configuration used either in the this material.
  93554. *
  93555. * If sets to null, the scene one is in use.
  93556. */
  93557. set: function (value) {
  93558. this._attachImageProcessingConfiguration(value);
  93559. // Ensure the effect will be rebuilt.
  93560. this._markAllSubMeshesAsTexturesDirty();
  93561. },
  93562. enumerable: true,
  93563. configurable: true
  93564. });
  93565. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  93566. /**
  93567. * Gets wether the color curves effect is enabled.
  93568. */
  93569. get: function () {
  93570. return this.imageProcessingConfiguration.colorCurvesEnabled;
  93571. },
  93572. /**
  93573. * Sets wether the color curves effect is enabled.
  93574. */
  93575. set: function (value) {
  93576. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  93577. },
  93578. enumerable: true,
  93579. configurable: true
  93580. });
  93581. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  93582. /**
  93583. * Gets wether the color grading effect is enabled.
  93584. */
  93585. get: function () {
  93586. return this.imageProcessingConfiguration.colorGradingEnabled;
  93587. },
  93588. /**
  93589. * Gets wether the color grading effect is enabled.
  93590. */
  93591. set: function (value) {
  93592. this.imageProcessingConfiguration.colorGradingEnabled = value;
  93593. },
  93594. enumerable: true,
  93595. configurable: true
  93596. });
  93597. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  93598. /**
  93599. * Gets wether tonemapping is enabled or not.
  93600. */
  93601. get: function () {
  93602. return this._imageProcessingConfiguration.toneMappingEnabled;
  93603. },
  93604. /**
  93605. * Sets wether tonemapping is enabled or not
  93606. */
  93607. set: function (value) {
  93608. this._imageProcessingConfiguration.toneMappingEnabled = value;
  93609. },
  93610. enumerable: true,
  93611. configurable: true
  93612. });
  93613. ;
  93614. ;
  93615. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  93616. /**
  93617. * The camera exposure used on this material.
  93618. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  93619. * This corresponds to a photographic exposure.
  93620. */
  93621. get: function () {
  93622. return this._imageProcessingConfiguration.exposure;
  93623. },
  93624. /**
  93625. * The camera exposure used on this material.
  93626. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  93627. * This corresponds to a photographic exposure.
  93628. */
  93629. set: function (value) {
  93630. this._imageProcessingConfiguration.exposure = value;
  93631. },
  93632. enumerable: true,
  93633. configurable: true
  93634. });
  93635. ;
  93636. ;
  93637. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  93638. /**
  93639. * Gets The camera contrast used on this material.
  93640. */
  93641. get: function () {
  93642. return this._imageProcessingConfiguration.contrast;
  93643. },
  93644. /**
  93645. * Sets The camera contrast used on this material.
  93646. */
  93647. set: function (value) {
  93648. this._imageProcessingConfiguration.contrast = value;
  93649. },
  93650. enumerable: true,
  93651. configurable: true
  93652. });
  93653. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  93654. /**
  93655. * Gets the Color Grading 2D Lookup Texture.
  93656. */
  93657. get: function () {
  93658. return this._imageProcessingConfiguration.colorGradingTexture;
  93659. },
  93660. /**
  93661. * Sets the Color Grading 2D Lookup Texture.
  93662. */
  93663. set: function (value) {
  93664. this.imageProcessingConfiguration.colorGradingTexture = value;
  93665. },
  93666. enumerable: true,
  93667. configurable: true
  93668. });
  93669. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  93670. /**
  93671. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  93672. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  93673. * 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;
  93674. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  93675. */
  93676. get: function () {
  93677. return this.imageProcessingConfiguration.colorCurves;
  93678. },
  93679. /**
  93680. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  93681. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  93682. * 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;
  93683. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  93684. */
  93685. set: function (value) {
  93686. this.imageProcessingConfiguration.colorCurves = value;
  93687. },
  93688. enumerable: true,
  93689. configurable: true
  93690. });
  93691. /**
  93692. * The entire material has been created in order to prevent overdraw.
  93693. * @returns false
  93694. */
  93695. BackgroundMaterial.prototype.needAlphaTesting = function () {
  93696. return true;
  93697. };
  93698. /**
  93699. * The entire material has been created in order to prevent overdraw.
  93700. * @returns true if blending is enable
  93701. */
  93702. BackgroundMaterial.prototype.needAlphaBlending = function () {
  93703. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  93704. };
  93705. /**
  93706. * Checks wether the material is ready to be rendered for a given mesh.
  93707. * @param mesh The mesh to render
  93708. * @param subMesh The submesh to check against
  93709. * @param useInstances Specify wether or not the material is used with instances
  93710. * @returns true if all the dependencies are ready (Textures, Effects...)
  93711. */
  93712. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  93713. var _this = this;
  93714. if (useInstances === void 0) { useInstances = false; }
  93715. if (subMesh.effect && this.isFrozen) {
  93716. if (this._wasPreviouslyReady) {
  93717. return true;
  93718. }
  93719. }
  93720. if (!subMesh._materialDefines) {
  93721. subMesh._materialDefines = new BackgroundMaterialDefines();
  93722. }
  93723. var scene = this.getScene();
  93724. var defines = subMesh._materialDefines;
  93725. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  93726. if (defines._renderId === scene.getRenderId()) {
  93727. return true;
  93728. }
  93729. }
  93730. var engine = scene.getEngine();
  93731. // Lights
  93732. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  93733. defines._needNormals = true;
  93734. // Textures
  93735. if (defines._areTexturesDirty) {
  93736. defines._needUVs = false;
  93737. if (scene.texturesEnabled) {
  93738. if (scene.getEngine().getCaps().textureLOD) {
  93739. defines.TEXTURELODSUPPORT = true;
  93740. }
  93741. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  93742. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  93743. return false;
  93744. }
  93745. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  93746. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  93747. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  93748. defines.OPACITYFRESNEL = this._opacityFresnel;
  93749. }
  93750. else {
  93751. defines.DIFFUSE = false;
  93752. defines.DIFFUSEHASALPHA = false;
  93753. defines.GAMMADIFFUSE = false;
  93754. defines.OPACITYFRESNEL = false;
  93755. }
  93756. var reflectionTexture = this._reflectionTexture;
  93757. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  93758. if (!reflectionTexture.isReadyOrNotBlocking()) {
  93759. return false;
  93760. }
  93761. defines.REFLECTION = true;
  93762. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  93763. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  93764. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  93765. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  93766. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  93767. defines.REFLECTIONBGR = this.switchToBGR;
  93768. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  93769. defines.INVERTCUBICMAP = true;
  93770. }
  93771. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  93772. switch (reflectionTexture.coordinatesMode) {
  93773. case BABYLON.Texture.CUBIC_MODE:
  93774. case BABYLON.Texture.INVCUBIC_MODE:
  93775. defines.REFLECTIONMAP_CUBIC = true;
  93776. break;
  93777. case BABYLON.Texture.EXPLICIT_MODE:
  93778. defines.REFLECTIONMAP_EXPLICIT = true;
  93779. break;
  93780. case BABYLON.Texture.PLANAR_MODE:
  93781. defines.REFLECTIONMAP_PLANAR = true;
  93782. break;
  93783. case BABYLON.Texture.PROJECTION_MODE:
  93784. defines.REFLECTIONMAP_PROJECTION = true;
  93785. break;
  93786. case BABYLON.Texture.SKYBOX_MODE:
  93787. defines.REFLECTIONMAP_SKYBOX = true;
  93788. break;
  93789. case BABYLON.Texture.SPHERICAL_MODE:
  93790. defines.REFLECTIONMAP_SPHERICAL = true;
  93791. break;
  93792. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  93793. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  93794. break;
  93795. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  93796. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  93797. break;
  93798. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  93799. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  93800. break;
  93801. }
  93802. if (this.reflectionFresnel) {
  93803. defines.REFLECTIONFRESNEL = true;
  93804. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  93805. this._reflectionControls.x = this.reflectionAmount;
  93806. this._reflectionControls.y = this.reflectionReflectance0;
  93807. this._reflectionControls.z = this.reflectionReflectance90;
  93808. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  93809. }
  93810. else {
  93811. defines.REFLECTIONFRESNEL = false;
  93812. defines.REFLECTIONFALLOFF = false;
  93813. }
  93814. }
  93815. else {
  93816. defines.REFLECTION = false;
  93817. defines.REFLECTIONFALLOFF = false;
  93818. defines.REFLECTIONBLUR = false;
  93819. defines.REFLECTIONMAP_3D = false;
  93820. defines.REFLECTIONMAP_SPHERICAL = false;
  93821. defines.REFLECTIONMAP_PLANAR = false;
  93822. defines.REFLECTIONMAP_CUBIC = false;
  93823. defines.REFLECTIONMAP_PROJECTION = false;
  93824. defines.REFLECTIONMAP_SKYBOX = false;
  93825. defines.REFLECTIONMAP_EXPLICIT = false;
  93826. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  93827. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  93828. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  93829. defines.INVERTCUBICMAP = false;
  93830. defines.REFLECTIONMAP_OPPOSITEZ = false;
  93831. defines.LODINREFLECTIONALPHA = false;
  93832. defines.GAMMAREFLECTION = false;
  93833. }
  93834. }
  93835. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  93836. defines.USERGBCOLOR = this._useRGBColor;
  93837. defines.NOISE = this._enableNoise;
  93838. }
  93839. if (defines._areImageProcessingDirty) {
  93840. if (!this._imageProcessingConfiguration.isReady()) {
  93841. return false;
  93842. }
  93843. this._imageProcessingConfiguration.prepareDefines(defines);
  93844. }
  93845. // Misc.
  93846. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  93847. // Values that need to be evaluated on every frame
  93848. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  93849. // Attribs
  93850. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  93851. if (mesh) {
  93852. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  93853. mesh.createNormals(true);
  93854. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  93855. }
  93856. }
  93857. }
  93858. // Get correct effect
  93859. if (defines.isDirty) {
  93860. defines.markAsProcessed();
  93861. scene.resetCachedMaterial();
  93862. // Fallbacks
  93863. var fallbacks = new BABYLON.EffectFallbacks();
  93864. if (defines.FOG) {
  93865. fallbacks.addFallback(0, "FOG");
  93866. }
  93867. if (defines.POINTSIZE) {
  93868. fallbacks.addFallback(1, "POINTSIZE");
  93869. }
  93870. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  93871. if (defines.NUM_BONE_INFLUENCERS > 0) {
  93872. fallbacks.addCPUSkinningFallback(0, mesh);
  93873. }
  93874. //Attributes
  93875. var attribs = [BABYLON.VertexBuffer.PositionKind];
  93876. if (defines.NORMAL) {
  93877. attribs.push(BABYLON.VertexBuffer.NormalKind);
  93878. }
  93879. if (defines.UV1) {
  93880. attribs.push(BABYLON.VertexBuffer.UVKind);
  93881. }
  93882. if (defines.UV2) {
  93883. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  93884. }
  93885. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  93886. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  93887. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  93888. "vFogInfos", "vFogColor", "pointSize",
  93889. "vClipPlane", "mBones",
  93890. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  93891. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  93892. "shadowLevel", "alpha",
  93893. "vBackgroundCenter", "vReflectionControl",
  93894. "vDiffuseInfos", "diffuseMatrix",
  93895. ];
  93896. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  93897. var uniformBuffers = ["Material", "Scene"];
  93898. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  93899. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  93900. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  93901. uniformsNames: uniforms,
  93902. uniformBuffersNames: uniformBuffers,
  93903. samplers: samplers,
  93904. defines: defines,
  93905. maxSimultaneousLights: this._maxSimultaneousLights
  93906. });
  93907. var onCompiled = function (effect) {
  93908. if (_this.onCompiled) {
  93909. _this.onCompiled(effect);
  93910. }
  93911. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  93912. };
  93913. var join = defines.toString();
  93914. subMesh.setEffect(scene.getEngine().createEffect("background", {
  93915. attributes: attribs,
  93916. uniformsNames: uniforms,
  93917. uniformBuffersNames: uniformBuffers,
  93918. samplers: samplers,
  93919. defines: join,
  93920. fallbacks: fallbacks,
  93921. onCompiled: onCompiled,
  93922. onError: this.onError,
  93923. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  93924. }, engine), defines);
  93925. this.buildUniformLayout();
  93926. }
  93927. if (!subMesh.effect || !subMesh.effect.isReady()) {
  93928. return false;
  93929. }
  93930. defines._renderId = scene.getRenderId();
  93931. this._wasPreviouslyReady = true;
  93932. return true;
  93933. };
  93934. /**
  93935. * Build the uniform buffer used in the material.
  93936. */
  93937. BackgroundMaterial.prototype.buildUniformLayout = function () {
  93938. // Order is important !
  93939. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  93940. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  93941. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  93942. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  93943. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  93944. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  93945. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  93946. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  93947. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  93948. this._uniformBuffer.addUniform("pointSize", 1);
  93949. this._uniformBuffer.addUniform("shadowLevel", 1);
  93950. this._uniformBuffer.addUniform("alpha", 1);
  93951. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  93952. this._uniformBuffer.addUniform("vReflectionControl", 4);
  93953. this._uniformBuffer.create();
  93954. };
  93955. /**
  93956. * Unbind the material.
  93957. */
  93958. BackgroundMaterial.prototype.unbind = function () {
  93959. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  93960. this._uniformBuffer.setTexture("diffuseSampler", null);
  93961. }
  93962. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  93963. this._uniformBuffer.setTexture("reflectionSampler", null);
  93964. }
  93965. _super.prototype.unbind.call(this);
  93966. };
  93967. /**
  93968. * Bind only the world matrix to the material.
  93969. * @param world The world matrix to bind.
  93970. */
  93971. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  93972. this._activeEffect.setMatrix("world", world);
  93973. };
  93974. /**
  93975. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  93976. * @param world The world matrix to bind.
  93977. * @param subMesh The submesh to bind for.
  93978. */
  93979. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  93980. var scene = this.getScene();
  93981. var defines = subMesh._materialDefines;
  93982. if (!defines) {
  93983. return;
  93984. }
  93985. var effect = subMesh.effect;
  93986. if (!effect) {
  93987. return;
  93988. }
  93989. this._activeEffect = effect;
  93990. // Matrices
  93991. this.bindOnlyWorldMatrix(world);
  93992. // Bones
  93993. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  93994. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  93995. if (mustRebind) {
  93996. this._uniformBuffer.bindToEffect(effect, "Material");
  93997. this.bindViewProjection(effect);
  93998. var reflectionTexture = this._reflectionTexture;
  93999. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  94000. // Texture uniforms
  94001. if (scene.texturesEnabled) {
  94002. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  94003. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  94004. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  94005. }
  94006. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  94007. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  94008. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  94009. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  94010. }
  94011. }
  94012. if (this.shadowLevel > 0) {
  94013. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  94014. }
  94015. this._uniformBuffer.updateFloat("alpha", this.alpha);
  94016. // Point size
  94017. if (this.pointsCloud) {
  94018. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  94019. }
  94020. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  94021. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  94022. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  94023. }
  94024. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  94025. // Textures
  94026. if (scene.texturesEnabled) {
  94027. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  94028. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  94029. }
  94030. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  94031. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  94032. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  94033. }
  94034. else if (!defines.REFLECTIONBLUR) {
  94035. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  94036. }
  94037. else {
  94038. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  94039. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  94040. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  94041. }
  94042. if (defines.REFLECTIONFRESNEL) {
  94043. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  94044. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  94045. }
  94046. }
  94047. }
  94048. // Clip plane
  94049. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  94050. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  94051. }
  94052. if (mustRebind || !this.isFrozen) {
  94053. if (scene.lightsEnabled) {
  94054. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  94055. }
  94056. // View
  94057. this.bindView(effect);
  94058. // Fog
  94059. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  94060. // image processing
  94061. this._imageProcessingConfiguration.bind(this._activeEffect);
  94062. }
  94063. this._uniformBuffer.update();
  94064. this._afterBind(mesh);
  94065. };
  94066. /**
  94067. * Dispose the material.
  94068. * @param forceDisposeEffect Force disposal of the associated effect.
  94069. * @param forceDisposeTextures Force disposal of the associated textures.
  94070. */
  94071. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  94072. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  94073. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  94074. if (forceDisposeTextures) {
  94075. if (this.diffuseTexture) {
  94076. this.diffuseTexture.dispose();
  94077. }
  94078. if (this.reflectionTexture) {
  94079. this.reflectionTexture.dispose();
  94080. }
  94081. }
  94082. this._renderTargets.dispose();
  94083. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  94084. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  94085. }
  94086. _super.prototype.dispose.call(this, forceDisposeEffect);
  94087. };
  94088. /**
  94089. * Clones the material.
  94090. * @param name The cloned name.
  94091. * @returns The cloned material.
  94092. */
  94093. BackgroundMaterial.prototype.clone = function (name) {
  94094. var _this = this;
  94095. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  94096. };
  94097. /**
  94098. * Serializes the current material to its JSON representation.
  94099. * @returns The JSON representation.
  94100. */
  94101. BackgroundMaterial.prototype.serialize = function () {
  94102. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  94103. serializationObject.customType = "BABYLON.BackgroundMaterial";
  94104. return serializationObject;
  94105. };
  94106. /**
  94107. * Gets the class name of the material
  94108. * @returns "BackgroundMaterial"
  94109. */
  94110. BackgroundMaterial.prototype.getClassName = function () {
  94111. return "BackgroundMaterial";
  94112. };
  94113. /**
  94114. * Parse a JSON input to create back a background material.
  94115. * @param source The JSON data to parse
  94116. * @param scene The scene to create the parsed material in
  94117. * @param rootUrl The root url of the assets the material depends upon
  94118. * @returns the instantiated BackgroundMaterial.
  94119. */
  94120. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  94121. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  94122. };
  94123. /**
  94124. * Standard reflectance value at parallel view angle.
  94125. */
  94126. BackgroundMaterial.StandardReflectance0 = 0.05;
  94127. /**
  94128. * Standard reflectance value at grazing angle.
  94129. */
  94130. BackgroundMaterial.StandardReflectance90 = 0.5;
  94131. __decorate([
  94132. BABYLON.serializeAsColor3()
  94133. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  94134. __decorate([
  94135. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  94136. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  94137. __decorate([
  94138. BABYLON.serialize()
  94139. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  94140. __decorate([
  94141. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  94142. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  94143. __decorate([
  94144. BABYLON.serializeAsColor3()
  94145. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  94146. __decorate([
  94147. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  94148. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  94149. __decorate([
  94150. BABYLON.serialize()
  94151. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  94152. __decorate([
  94153. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  94154. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  94155. __decorate([
  94156. BABYLON.serializeAsColor3()
  94157. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  94158. __decorate([
  94159. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  94160. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  94161. __decorate([
  94162. BABYLON.serialize()
  94163. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  94164. __decorate([
  94165. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  94166. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  94167. __decorate([
  94168. BABYLON.serializeAsTexture()
  94169. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  94170. __decorate([
  94171. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94172. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  94173. __decorate([
  94174. BABYLON.serialize()
  94175. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  94176. __decorate([
  94177. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94178. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  94179. __decorate([
  94180. BABYLON.serializeAsTexture()
  94181. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  94182. __decorate([
  94183. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94184. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  94185. __decorate([
  94186. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94187. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  94188. __decorate([
  94189. BABYLON.serialize()
  94190. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  94191. __decorate([
  94192. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94193. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  94194. __decorate([
  94195. BABYLON.serialize()
  94196. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  94197. __decorate([
  94198. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94199. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  94200. __decorate([
  94201. BABYLON.serializeAsVector3()
  94202. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  94203. __decorate([
  94204. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94205. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  94206. __decorate([
  94207. BABYLON.serialize()
  94208. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  94209. __decorate([
  94210. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94211. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  94212. __decorate([
  94213. BABYLON.serialize()
  94214. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  94215. __decorate([
  94216. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94217. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  94218. __decorate([
  94219. BABYLON.serialize()
  94220. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  94221. __decorate([
  94222. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94223. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  94224. __decorate([
  94225. BABYLON.serialize()
  94226. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  94227. __decorate([
  94228. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94229. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  94230. __decorate([
  94231. BABYLON.serialize()
  94232. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  94233. __decorate([
  94234. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94235. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  94236. __decorate([
  94237. BABYLON.serialize()
  94238. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  94239. __decorate([
  94240. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94241. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  94242. __decorate([
  94243. BABYLON.serialize()
  94244. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  94245. __decorate([
  94246. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94247. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  94248. __decorate([
  94249. BABYLON.serialize()
  94250. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  94251. __decorate([
  94252. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94253. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  94254. __decorate([
  94255. BABYLON.serialize()
  94256. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  94257. __decorate([
  94258. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94259. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  94260. __decorate([
  94261. BABYLON.serializeAsImageProcessingConfiguration()
  94262. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  94263. return BackgroundMaterial;
  94264. }(BABYLON.PushMaterial));
  94265. BABYLON.BackgroundMaterial = BackgroundMaterial;
  94266. })(BABYLON || (BABYLON = {}));
  94267. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  94268. "use strict";
  94269. var __assign = (this && this.__assign) || Object.assign || function(t) {
  94270. for (var s, i = 1, n = arguments.length; i < n; i++) {
  94271. s = arguments[i];
  94272. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  94273. t[p] = s[p];
  94274. }
  94275. return t;
  94276. };
  94277. var BABYLON;
  94278. (function (BABYLON) {
  94279. /**
  94280. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  94281. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  94282. * It also helps with the default setup of your imageProcessing configuration.
  94283. */
  94284. var EnvironmentHelper = /** @class */ (function () {
  94285. /**
  94286. * constructor
  94287. * @param options
  94288. * @param scene The scene to add the material to
  94289. */
  94290. function EnvironmentHelper(options, scene) {
  94291. var _this = this;
  94292. this._errorHandler = function (message, exception) {
  94293. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  94294. };
  94295. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  94296. this._scene = scene;
  94297. this.onErrorObservable = new BABYLON.Observable();
  94298. this._setupBackground();
  94299. this._setupImageProcessing();
  94300. }
  94301. /**
  94302. * Creates the default options for the helper.
  94303. */
  94304. EnvironmentHelper._getDefaultOptions = function () {
  94305. return {
  94306. createGround: true,
  94307. groundSize: 15,
  94308. groundTexture: this._groundTextureCDNUrl,
  94309. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  94310. groundOpacity: 0.9,
  94311. enableGroundShadow: true,
  94312. groundShadowLevel: 0.5,
  94313. enableGroundMirror: false,
  94314. groundMirrorSizeRatio: 0.3,
  94315. groundMirrorBlurKernel: 64,
  94316. groundMirrorAmount: 1,
  94317. groundMirrorFresnelWeight: 1,
  94318. groundMirrorFallOffDistance: 0,
  94319. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  94320. groundYBias: 0.00001,
  94321. createSkybox: true,
  94322. skyboxSize: 20,
  94323. skyboxTexture: this._skyboxTextureCDNUrl,
  94324. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  94325. backgroundYRotation: 0,
  94326. sizeAuto: true,
  94327. rootPosition: BABYLON.Vector3.Zero(),
  94328. setupImageProcessing: true,
  94329. environmentTexture: this._environmentTextureCDNUrl,
  94330. cameraExposure: 0.8,
  94331. cameraContrast: 1.2,
  94332. toneMappingEnabled: true,
  94333. };
  94334. };
  94335. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  94336. /**
  94337. * Gets the root mesh created by the helper.
  94338. */
  94339. get: function () {
  94340. return this._rootMesh;
  94341. },
  94342. enumerable: true,
  94343. configurable: true
  94344. });
  94345. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  94346. /**
  94347. * Gets the skybox created by the helper.
  94348. */
  94349. get: function () {
  94350. return this._skybox;
  94351. },
  94352. enumerable: true,
  94353. configurable: true
  94354. });
  94355. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  94356. /**
  94357. * Gets the skybox texture created by the helper.
  94358. */
  94359. get: function () {
  94360. return this._skyboxTexture;
  94361. },
  94362. enumerable: true,
  94363. configurable: true
  94364. });
  94365. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  94366. /**
  94367. * Gets the skybox material created by the helper.
  94368. */
  94369. get: function () {
  94370. return this._skyboxMaterial;
  94371. },
  94372. enumerable: true,
  94373. configurable: true
  94374. });
  94375. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  94376. /**
  94377. * Gets the ground mesh created by the helper.
  94378. */
  94379. get: function () {
  94380. return this._ground;
  94381. },
  94382. enumerable: true,
  94383. configurable: true
  94384. });
  94385. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  94386. /**
  94387. * Gets the ground texture created by the helper.
  94388. */
  94389. get: function () {
  94390. return this._groundTexture;
  94391. },
  94392. enumerable: true,
  94393. configurable: true
  94394. });
  94395. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  94396. /**
  94397. * Gets the ground mirror created by the helper.
  94398. */
  94399. get: function () {
  94400. return this._groundMirror;
  94401. },
  94402. enumerable: true,
  94403. configurable: true
  94404. });
  94405. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  94406. /**
  94407. * Gets the ground mirror render list to helps pushing the meshes
  94408. * you wish in the ground reflection.
  94409. */
  94410. get: function () {
  94411. if (this._groundMirror) {
  94412. return this._groundMirror.renderList;
  94413. }
  94414. return null;
  94415. },
  94416. enumerable: true,
  94417. configurable: true
  94418. });
  94419. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  94420. /**
  94421. * Gets the ground material created by the helper.
  94422. */
  94423. get: function () {
  94424. return this._groundMaterial;
  94425. },
  94426. enumerable: true,
  94427. configurable: true
  94428. });
  94429. /**
  94430. * Updates the background according to the new options
  94431. * @param options
  94432. */
  94433. EnvironmentHelper.prototype.updateOptions = function (options) {
  94434. var newOptions = __assign({}, this._options, options);
  94435. if (this._ground && !newOptions.createGround) {
  94436. this._ground.dispose();
  94437. this._ground = null;
  94438. }
  94439. if (this._groundMaterial && !newOptions.createGround) {
  94440. this._groundMaterial.dispose();
  94441. this._groundMaterial = null;
  94442. }
  94443. if (this._groundTexture) {
  94444. if (this._options.groundTexture != newOptions.groundTexture) {
  94445. this._groundTexture.dispose();
  94446. this._groundTexture = null;
  94447. }
  94448. }
  94449. if (this._skybox && !newOptions.createSkybox) {
  94450. this._skybox.dispose();
  94451. this._skybox = null;
  94452. }
  94453. if (this._skyboxMaterial && !newOptions.createSkybox) {
  94454. this._skyboxMaterial.dispose();
  94455. this._skyboxMaterial = null;
  94456. }
  94457. if (this._skyboxTexture) {
  94458. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  94459. this._skyboxTexture.dispose();
  94460. this._skyboxTexture = null;
  94461. }
  94462. }
  94463. if (this._groundMirror && !newOptions.enableGroundMirror) {
  94464. this._groundMirror.dispose();
  94465. this._groundMirror = null;
  94466. }
  94467. if (this._scene.environmentTexture) {
  94468. if (this._options.environmentTexture != newOptions.environmentTexture) {
  94469. this._scene.environmentTexture.dispose();
  94470. }
  94471. }
  94472. this._options = newOptions;
  94473. this._setupBackground();
  94474. this._setupImageProcessing();
  94475. };
  94476. /**
  94477. * Sets the primary color of all the available elements.
  94478. * @param color
  94479. */
  94480. EnvironmentHelper.prototype.setMainColor = function (color) {
  94481. if (this.groundMaterial) {
  94482. this.groundMaterial.primaryColor = color;
  94483. }
  94484. if (this.skyboxMaterial) {
  94485. this.skyboxMaterial.primaryColor = color;
  94486. }
  94487. if (this.groundMirror) {
  94488. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  94489. }
  94490. };
  94491. /**
  94492. * Setup the image processing according to the specified options.
  94493. */
  94494. EnvironmentHelper.prototype._setupImageProcessing = function () {
  94495. if (this._options.setupImageProcessing) {
  94496. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  94497. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  94498. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  94499. this._setupEnvironmentTexture();
  94500. }
  94501. };
  94502. /**
  94503. * Setup the environment texture according to the specified options.
  94504. */
  94505. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  94506. if (this._scene.environmentTexture) {
  94507. return;
  94508. }
  94509. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  94510. this._scene.environmentTexture = this._options.environmentTexture;
  94511. return;
  94512. }
  94513. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  94514. this._scene.environmentTexture = environmentTexture;
  94515. };
  94516. /**
  94517. * Setup the background according to the specified options.
  94518. */
  94519. EnvironmentHelper.prototype._setupBackground = function () {
  94520. if (!this._rootMesh) {
  94521. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  94522. }
  94523. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  94524. var sceneSize = this._getSceneSize();
  94525. if (this._options.createGround) {
  94526. this._setupGround(sceneSize);
  94527. this._setupGroundMaterial();
  94528. this._setupGroundDiffuseTexture();
  94529. if (this._options.enableGroundMirror) {
  94530. this._setupGroundMirrorTexture(sceneSize);
  94531. }
  94532. this._setupMirrorInGroundMaterial();
  94533. }
  94534. if (this._options.createSkybox) {
  94535. this._setupSkybox(sceneSize);
  94536. this._setupSkyboxMaterial();
  94537. this._setupSkyboxReflectionTexture();
  94538. }
  94539. this._rootMesh.position.x = sceneSize.rootPosition.x;
  94540. this._rootMesh.position.z = sceneSize.rootPosition.z;
  94541. this._rootMesh.position.y = sceneSize.rootPosition.y;
  94542. };
  94543. /**
  94544. * Get the scene sizes according to the setup.
  94545. */
  94546. EnvironmentHelper.prototype._getSceneSize = function () {
  94547. var _this = this;
  94548. var groundSize = this._options.groundSize;
  94549. var skyboxSize = this._options.skyboxSize;
  94550. var rootPosition = this._options.rootPosition;
  94551. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  94552. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  94553. }
  94554. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  94555. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  94556. });
  94557. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  94558. if (this._options.sizeAuto) {
  94559. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  94560. this._scene.activeCamera.upperRadiusLimit) {
  94561. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  94562. skyboxSize = groundSize;
  94563. }
  94564. var sceneDiagonalLenght = sceneDiagonal.length();
  94565. if (sceneDiagonalLenght > groundSize) {
  94566. groundSize = sceneDiagonalLenght * 2;
  94567. skyboxSize = groundSize;
  94568. }
  94569. // 10 % bigger.
  94570. groundSize *= 1.1;
  94571. skyboxSize *= 1.5;
  94572. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  94573. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  94574. }
  94575. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  94576. };
  94577. /**
  94578. * Setup the ground according to the specified options.
  94579. */
  94580. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  94581. var _this = this;
  94582. if (!this._ground) {
  94583. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  94584. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  94585. this._ground.parent = this._rootMesh;
  94586. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  94587. }
  94588. this._ground.receiveShadows = this._options.enableGroundShadow;
  94589. };
  94590. /**
  94591. * Setup the ground material according to the specified options.
  94592. */
  94593. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  94594. if (!this._groundMaterial) {
  94595. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  94596. }
  94597. this._groundMaterial.alpha = this._options.groundOpacity;
  94598. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  94599. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  94600. this._groundMaterial.primaryLevel = 1;
  94601. this._groundMaterial.primaryColor = this._options.groundColor;
  94602. this._groundMaterial.secondaryLevel = 0;
  94603. this._groundMaterial.tertiaryLevel = 0;
  94604. this._groundMaterial.useRGBColor = false;
  94605. this._groundMaterial.enableNoise = true;
  94606. if (this._ground) {
  94607. this._ground.material = this._groundMaterial;
  94608. }
  94609. };
  94610. /**
  94611. * Setup the ground diffuse texture according to the specified options.
  94612. */
  94613. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  94614. if (!this._groundMaterial) {
  94615. return;
  94616. }
  94617. if (this._groundTexture) {
  94618. return;
  94619. }
  94620. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  94621. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  94622. return;
  94623. }
  94624. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  94625. diffuseTexture.gammaSpace = false;
  94626. diffuseTexture.hasAlpha = true;
  94627. this._groundMaterial.diffuseTexture = diffuseTexture;
  94628. };
  94629. /**
  94630. * Setup the ground mirror texture according to the specified options.
  94631. */
  94632. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  94633. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94634. if (!this._groundMirror) {
  94635. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  94636. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  94637. this._groundMirror.anisotropicFilteringLevel = 1;
  94638. this._groundMirror.wrapU = wrapping;
  94639. this._groundMirror.wrapV = wrapping;
  94640. this._groundMirror.gammaSpace = false;
  94641. if (this._groundMirror.renderList) {
  94642. for (var i = 0; i < this._scene.meshes.length; i++) {
  94643. var mesh = this._scene.meshes[i];
  94644. if (mesh !== this._ground &&
  94645. mesh !== this._skybox &&
  94646. mesh !== this._rootMesh) {
  94647. this._groundMirror.renderList.push(mesh);
  94648. }
  94649. }
  94650. }
  94651. }
  94652. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  94653. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  94654. };
  94655. /**
  94656. * Setup the ground to receive the mirror texture.
  94657. */
  94658. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  94659. if (this._groundMaterial) {
  94660. this._groundMaterial.reflectionTexture = this._groundMirror;
  94661. this._groundMaterial.reflectionFresnel = true;
  94662. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  94663. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  94664. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  94665. }
  94666. };
  94667. /**
  94668. * Setup the skybox according to the specified options.
  94669. */
  94670. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  94671. var _this = this;
  94672. if (!this._skybox) {
  94673. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  94674. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  94675. }
  94676. this._skybox.parent = this._rootMesh;
  94677. };
  94678. /**
  94679. * Setup the skybox material according to the specified options.
  94680. */
  94681. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  94682. if (!this._skybox) {
  94683. return;
  94684. }
  94685. if (!this._skyboxMaterial) {
  94686. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  94687. }
  94688. this._skyboxMaterial.useRGBColor = false;
  94689. this._skyboxMaterial.primaryLevel = 1;
  94690. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  94691. this._skyboxMaterial.secondaryLevel = 0;
  94692. this._skyboxMaterial.tertiaryLevel = 0;
  94693. this._skyboxMaterial.enableNoise = true;
  94694. this._skybox.material = this._skyboxMaterial;
  94695. };
  94696. /**
  94697. * Setup the skybox reflection texture according to the specified options.
  94698. */
  94699. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  94700. if (!this._skyboxMaterial) {
  94701. return;
  94702. }
  94703. if (this._skyboxTexture) {
  94704. return;
  94705. }
  94706. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  94707. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  94708. return;
  94709. }
  94710. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  94711. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  94712. this._skyboxTexture.gammaSpace = false;
  94713. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  94714. };
  94715. /**
  94716. * Dispose all the elements created by the Helper.
  94717. */
  94718. EnvironmentHelper.prototype.dispose = function () {
  94719. if (this._groundMaterial) {
  94720. this._groundMaterial.dispose(true, true);
  94721. }
  94722. if (this._skyboxMaterial) {
  94723. this._skyboxMaterial.dispose(true, true);
  94724. }
  94725. this._rootMesh.dispose(false);
  94726. };
  94727. /**
  94728. * Default ground texture URL.
  94729. */
  94730. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  94731. /**
  94732. * Default skybox texture URL.
  94733. */
  94734. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  94735. /**
  94736. * Default environment texture URL.
  94737. */
  94738. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  94739. return EnvironmentHelper;
  94740. }());
  94741. BABYLON.EnvironmentHelper = EnvironmentHelper;
  94742. })(BABYLON || (BABYLON = {}));
  94743. //# sourceMappingURL=babylon.environmentHelper.js.map
  94744. "use strict";
  94745. var BABYLON;
  94746. (function (BABYLON) {
  94747. /**
  94748. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  94749. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  94750. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  94751. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  94752. */
  94753. var VideoDome = /** @class */ (function (_super) {
  94754. __extends(VideoDome, _super);
  94755. /**
  94756. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  94757. * @param name Element's name, child elements will append suffixes for their own names.
  94758. * @param urlsOrVideo
  94759. * @param options An object containing optional or exposed sub element properties:
  94760. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  94761. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  94762. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  94763. * @param options **loop=true** Automatically loop video on end.
  94764. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  94765. */
  94766. function VideoDome(name, urlsOrVideo, options, scene) {
  94767. var _this = _super.call(this, name, scene) || this;
  94768. // set defaults and manage values
  94769. name = name || "videoDome";
  94770. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  94771. options.clickToPlay = Boolean(options.clickToPlay);
  94772. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  94773. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  94774. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  94775. // create
  94776. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  94777. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  94778. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  94779. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  94780. flat: false,
  94781. radius: options.size,
  94782. subdivisions: options.resolution,
  94783. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  94784. }, scene);
  94785. // configure material
  94786. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  94787. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  94788. material.reflectionTexture = _this._videoTexture;
  94789. material.useEquirectangularFOV = true;
  94790. material.fovMultiplier = 1.0;
  94791. // configure mesh
  94792. _this._mesh.material = material;
  94793. _this._mesh.parent = _this;
  94794. // optional configuration
  94795. if (options.clickToPlay) {
  94796. scene.onPointerUp = function () {
  94797. _this._videoTexture.video.play();
  94798. };
  94799. }
  94800. return _this;
  94801. }
  94802. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  94803. /**
  94804. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  94805. * Also see the options.resolution property.
  94806. */
  94807. get: function () {
  94808. return this._material.fovMultiplier;
  94809. },
  94810. set: function (value) {
  94811. this._material.fovMultiplier = value;
  94812. },
  94813. enumerable: true,
  94814. configurable: true
  94815. });
  94816. /**
  94817. * Releases resources associated with this node.
  94818. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  94819. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  94820. */
  94821. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  94822. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  94823. this._videoTexture.dispose();
  94824. this._mesh.dispose();
  94825. this._material.dispose();
  94826. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  94827. };
  94828. return VideoDome;
  94829. }(BABYLON.Node));
  94830. BABYLON.VideoDome = VideoDome;
  94831. })(BABYLON || (BABYLON = {}));
  94832. //# sourceMappingURL=babylon.videoDome.js.map
  94833. 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\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(GEOMETRYAA)\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#ifdef GEOMETRYAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#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#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef GEOMETRYAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\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=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(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\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\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","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.,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 float stopFactor;\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) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\noutColor=vec4(0.,0.,0.,0.);\noutSize=0.;\noutDirection=direction;\nreturn;\n}\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;\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*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\noutColor=color;\noutSize=size;\noutDirection=direction+gravity*timeDelta;\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#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\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}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\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,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n"};
  94834. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\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};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=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,geometricRoughnessFactor,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 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,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","kernelBlurFragment":"#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\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};"};
  94835. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  94836. globalObject["BABYLON"] = BABYLON;
  94837. //backwards compatibility
  94838. if(typeof earcut !== 'undefined') {
  94839. globalObject["Earcut"] = {
  94840. earcut: earcut
  94841. };
  94842. }
  94843. return BABYLON;
  94844. });